Cannot get Toast from EditText - java

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.

Related

How and Where can a declaration go so it can be used by two methods in Android Studio

I'm a newcomer to Java and Android Studio so am still learning, so sorry if this question is simplistic. I have recently discovered that as an alternative to coding an onClickListener in the activity.java file to respond to a button click, it can be done more simply with an android:onClick="method name" in the corresponding layout.xml file. I have already looked at this site's questions relating to the pros and cons of each method, but that is not my problem. My problem is, where and how can I declare a text field that is used by two methods without having to declare it in each method?
The code that follows is as minimal as possible. There are two buttons and one text view. If I attempt to put "TextView themessage = (TextView) findViewById(R.id.message);" anywhere other than in both methods, I get the dreaded "Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference".
Is there anywhere and any way to make a single declaration that can be used by both methods without generating this exception?
Extract from the .xml file
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:id="#+id/topbutton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="88dp"
android:onClick="doit"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="***"
android:id="#+id/message"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Again"
android:id="#+id/againbutton"
android:layout_below="#+id/message"
android:layout_centerHorizontal="true"
android:layout_marginTop="63dp"
android:onClick="starit"/>
Top end extract from the .java file
package com.example.owner.clickme;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doit (View v)
{
TextView themessage = (TextView) findViewById(R.id.message);
themessage.setText("Well clicked, Sir!");
}
public void starit (View v)
{
TextView themessage = (TextView) findViewById(R.id.message);
themessage.setText("****");
}
.
. etc.
It is common practice in Android to instantiate any Views within the onCreate, or where you inflate the main content view.
So, make a field inside of MainActivity like so
private TextView themessage;
Within onCreate get the TextView
theMessage = (TextView) findViewById(R.id.message);
Then you are free to use theMessage across both methods.
All in all, it looks like this
public class MainActivity extends AppCompatActivity
{
private TextView themessage;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
themessage = (TextView) findViewById(R.id.message);
}
public void doit (View v)
{
themessage.setText("Well clicked, Sir!");
}
public void starit (View v)
{
themessage.setText("****");
}
}
I think what you want to do is have the TextField as member of your activity class.
Something like that probably
public class MainActivity extends AppCompatActivity {
TextView theMessage;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theMessage = (TextView) findViewById(R.id.message);
}
public void doit () {
theMessage.setText("Well clicked, Sir!");
}
public void starit() {
themessage.setText("****");
}
}

Access fragment from activity besides main activity

I have an existing application that I am trying to modify and could really use some help.
It is a chat application. The original flow of the application was as follows:
Launch-> Splash Screen Activity-> MainActivity (extending Actionbar Sherlock)
Once in the main activity the default fragment is the ChatRoomFragment. From there you can select different tabs and interact with the application.
What I would like to change about the flow to is the following:
Launch->Splash Screen Activity-> Terms of Service/Sign -> MainMenu->MainActivity
I have created the mainmenu layout to contain 4 buttons. Join, Search, Profile, Settings
Here is the problem. My Join button works fine, onClick simply triggers the intent to start MainActivity and and the chat room loads. From this screen you can access the different tabs and fragments within the application.
However, I now would like to have the "search" button set to open a dialog. With a editText field and a search button. Upon clicking search it should pass the search string to the PlacesSearchFragment and populate results.
I copied the code from within my application where this search is normally completed (inside the ChatRoomsFragment but it will not work from within my mainMenu Activity.
How do I start the new fragment from the menu activity??
Code Below:
menuActivity.java
package com.peekatucorp.peekatu;
//import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class menuActivity extends Activity implements ActionBar.TabListener {
Button b1;
Button b2;
Button b3;
EditText txtsearch;
final private static int DIALOG_LOGIN = 1;
final private static int DIALOG_FORGET = 2;
final private static int DIALOG_SEARCH = 3;
private android.app.FragmentTransaction ft;
#Override
public void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = this.getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
if(preferences.getString("Username", "").length()<=0 || preferences.getString("loggedin_user", "").length()<=0){
showDialog(DIALOG_LOGIN);
}
b1= (Button) this.findViewById(R.id.joinbutton);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(menuActivity.this, MainActivity.class);
menuActivity.this.startActivity(intent);
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("loadMain", "1");
editor.commit();
}
});
b2= (Button) this.findViewById(R.id.searchbutton);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showDialog(DIALOG_SEARCH);
}
}
);
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog dialogDetails = null;
switch (id) {
case DIALOG_LOGIN:
if(true){
....some code}
break;
case DIALOG_FORGET:
if(true){
...some code
}
break;
case DIALOG_SEARCH:
if(true){
LayoutInflater inflater = LayoutInflater.from(this);
View dialogview = inflater.inflate(R.layout.menusearch_layout, null);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
dialogbuilder.setTitle("Where ya headed?");
dialogbuilder.setView(dialogview);
dialogDetails = dialogbuilder.create();
}
}
return dialogDetails;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_LOGIN:
...some code
break;
case DIALOG_SEARCH:
final AlertDialog alertDialog3 = (AlertDialog) dialog;
final Button btnLocalsearch = (Button) alertDialog3
.findViewById(R.id.local_search);
final Button btnSearch = (Button) alertDialog3
.findViewById(R.id.btn_search);
final EditText txtsearch = (EditText) alertDialog3
.findViewById(R.id.txtsearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//showDialog(DIALOG_FORGET);
//alertDialog3.dismiss();
// TODO Auto-generated method stub
menuActivity m = com.peekatucorp.peekatu.menuActivity.this;
final TabInfo tab = com.peekatucorp.peekatu.menuActivity.this.getCurrentTabInfo();
final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(txtsearch.getText().toString(),"1");
// fragment.setText(characters[position]);
// second, you push the fragment. It becomes visible and the up button is
// shown
m.pushFragment(tab, fragment);
}
});
}
mainmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_width="wrap_content"
android:layout_height="65dp"
android:layout_marginLeft="10dip"
android:src="#drawable/registration_banner3"
android:id="#+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Join Chat"
android:id="#+id/joinbutton"
android:layout_below="#+id/imageView"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/searchbutton"
android:layout_below="#+id/joinbutton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="55dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profile"
android:id="#+id/prfbutton"
android:layout_below="#+id/searchbutton"
android:layout_marginTop="72dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="#+id/searchbutton"
android:layout_alignStart="#+id/searchbutton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
android:id="#+id/settingsbutton"
android:layout_below="#+id/prfbutton"
android:layout_marginTop="51dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout android:id="#+id/footer"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#layout/footer_repeat"
android:layout_alignParentBottom="true">
</LinearLayout>
</RelativeLayout>
ChatRoomsFragment.java (WORKING FRAGMENT)
public class ChatRoomsFragment extends SherlockFragment implements OnItemSelectedListener{
String[] items;
List<String> list;
Spinner my_spin;
RadioButton mainRoom;
RadioButton customRoom;
RadioButton GPSRoom;
EditText privateRoom;
EditText GPSsearch;
TextView GPSaddress;
String selected_public;
Context contexxt;
ImageLoader imageLoader;
public AbstractTabStackNavigationActivity navact;
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
setRetainInstance(true);
final View v = inflater.inflate(R.layout.chatrooms_layout, container, false);
contexxt = v.getContext();
// setRetainInstance(true);
SharedPreferences preferences = v.getContext().getSharedPreferences("MyPreferences", this.getActivity().MODE_PRIVATE);
my_spin=(Spinner)v.findViewById(R.id.spinner1);
my_spin.setOnItemSelectedListener(this);
selected_public = preferences.getString("selected_room", "Adult Lobby");
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
GPSsearch = (EditText)v.findViewById(R.id.cr_gps_search);
GPSaddress = (TextView)v.findViewById(R.id.cr_gps_address);
GPSaddress.setText(preferences.getString("user_location", ""));
Button search_go = (Button)v.findViewById(R.id.cr_go_search);
Button address_go = (Button)v.findViewById(R.id.cr_go_address);
Button changeroom = (Button)v.findViewById(R.id.cr_changeroom);
//Button changeroom2 = (Button)v.findViewById(R.id.cr_changeRoom2);
search_go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
MainActivity m = (MainActivity)getActivity();
final TabInfo tab = m.getCurrentTabInfo();
final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(GPSsearch.getText().toString(),"1");
// fragment.setText(characters[position]);
// second, you push the fragment. It becomes visible and the up button is
// shown
m.pushFragment(tab, fragment);
}
});
Can someone please explain to me how to get it to load the fragment. Thank you. Let me know if I am leaving out any relevant code. Im getting a null pointer exception as my error.
Well, first of all, here is the code I was talking about in my comment:
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
menuActivity m = dialog.getOwningActivity();
final TabInfo tab = m.getCurrentTabInfo();
final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(txtsearch.getText().toString(),"1");
m.pushFragment(tab, fragment);
...
However, now that I type this up, it doesn't make sense that the NPE was on the call to pushFragment like you said. If the activity outer-class reference was really the null pointer, then it should have crashed a few lines earlier, calling getCurrentTabInfo. Thus I don't think this code change will help. Please take a second look at the stack you are seeing, and tell me what line the NPE is happening on.

Unhandled exception type when trying to use buttons as Nav menu

I am trying to link different buttons to different activities. so in effect creating a navigation menu.
I am trying to use less code so am trying to create one function i can pass values to in order to dynamically identify the buttons id and give it a link to the activity.
Here is my 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" >
<Button
android:id="#+id/nav1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/nav1" />
<Button
android:id="#+id/nav2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/nav1"
android:text="#string/nav2" />
</RelativeLayout>
Here is my Java:
package com.example.myfirstapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Nav extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
String nav1 = "nav1";
String nav2 = "nav2";
String MainActivity = "MainActivity";
String SQLite = "SQLite";
navButton(nav1, MainActivity);
navButton(nav2, SQLite);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_nav, menu);
return true;
}
private void navButton(String buttonId, String activityName){
String bId = buttonId;
final Class<?> aName = Class.forName(activityName);
int resId = getResources().getIdentifier(bId, "id", getPackageName());
Button b = (Button) findViewById(resId);
OnClickListener onClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(Nav.this, aName);
startActivity(i);
}};
b.setOnClickListener(onClickListener);
}
}
I am getting an error on line:
final Class<?> aName = Class.forName(activityName);
And it says:
Unhandled exception type ClassNotFoundException
Or quite simply whats the best way to do this
Any time I use Class.forName I pass in a qualified name, e.g. "mypackage.myclass". I'm not sure if it works with an unqualified name.
In any case, why pass in the string and then do a forName? Why not change the signature to take a Class object and just pass in MainActivity.class, etc? Then you'd catch any missing classes or spelling errors at compile time instead of run time.
Update in response to comment
public class Nav extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
navButton("nav1", MainActivity.class);
navButton("nav2", SQLite.class);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_nav, menu);
return true;
}
private void navButton(String buttonId, Class aName){
String bId = buttonId;
// aName now passed in so doesn't need to be looked up
... etc ...
}
}
I think the above should compile and run. I haven't tried it but I've done similar things. Depending on how your packages are set up, you may need to import MainActivity and SQLite, or fully quality them, in order to take the .class.
Have you defined your activities in your application's AndroidManifest.xml?
You aren't catching the checked exception ClassNotFoundException. You need to wrap the relevant code in a try/catch block, e.g.
try {
final Class<?> aName = Class.forName(activityName);
//etc...
} catch (ClassNotFoundException e) {
//Do whatever cleanup you have to do in case this situation occurs.
}
This seems like an unusually awkward way to set a click listener, though. Why can you not just pass in the class itself to your navButton method instead of doing reflection (which should always be a last resort if there's an alternative)?

how to include list along side other UI elements? (Android)

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

Application not working, beginner

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).

Categories