I have this activity with EditViews and button. When the button is pressed I move on to a new activity. the problem is when the back button is pressed. The EditViews are not visible. What is expected is that the views and the text that was entered are visible. Also The buttons that appear are from the second activity and not the first.
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.ammar.android.dailyjobsiteinspection2.MainActivity1Activity">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="350dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/scrollView">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/linearLayout">
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:visibility="invisible" />
<EditText
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/editText"
android:layout_gravity="center"
android:hint="Inspector ID"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:text="New Text"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:visibility="invisible" />
<EditText
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/editText2"
android:layout_gravity="center"
android:hint="Site Name" />
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:text="New Text"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal"
android:visibility="invisible"
android:layout_weight="1" />
<EditText
android:layout_width="fill_parent"
android:layout_height="70dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:id="#+id/editText3"
android:layout_gravity="center"
android:hint="Site Address" />
<Button
android:layout_width="160dp"
android:layout_height="60dp"
android:text="Start"
android:id="#+id/button3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:onClick="start"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
Here is the Java code:
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity1Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_activity1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void start(View view){
EditText editText1 = (EditText) findViewById(R.id.editText);
EditText editText2 = (EditText) findViewById(R.id.editText2);
EditText editText3 = (EditText) findViewById(R.id.editText3);
if(!allFieldsEntered(editText1, editText2, editText3)){
com.ammar.android.dailyjobsiteinspection2.Message.message(this, "All fields must be filled before starting an Audit ");
}else{
Intent intent = new Intent(this, MainActivity11Activity.class);
Bundle bundle = getDataBundle(editText1, editText2, editText3);
intent.putExtras(bundle);
setContentView(R.layout.activity_main_activity11);
startActivity(intent);
}
}
private Bundle getDataBundle(EditText editText1, EditText editText2, EditText editText3) {
Bundle bundle = new Bundle();
bundle.putString(MainActivity.INSPECTORID, editText1.getText().toString());
bundle.putString(MainActivity.SITENAME, editText2.getText().toString());
bundle.putString(MainActivity.SITEADDRESS, editText3.getText().toString());
return bundle;
}
private boolean allFieldsEntered(EditText editText1, EditText editText2, EditText editText3) {
return !(editText1.getText().toString().matches("")
|| editText2.getText().toString().matches("")
|| editText3.getText().toString().matches(""));
}
}
Here is the second activity:
<LinearLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.ammar.android.dailyjobsiteinspection2.MainActivity11Activity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/scrollView"
android:layout_gravity="center_horizontal"
android:layout_weight="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layout"></LinearLayout>
</ScrollView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="#+id/layout2">
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:text="New Text"
android:id="#+id/textView4"
android:layout_weight="1"
android:visibility="invisible" />
<Button
android:layout_width="160dp"
android:layout_height="fill_parent"
android:text="Save"
android:id="#+id/button4"
android:onClick="save" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView5"
android:layout_weight="1"
android:visibility="invisible"/>
<Button
android:layout_width="160dp"
android:layout_height="fill_parent"
android:text="Submit"
android:id="#+id/button5"
android:onClick="submit" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView6"
android:layout_weight="1"
android:visibility="invisible"/>
</LinearLayout>
</LinearLayout>
and the Java code:
import android.app.ActionBar;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity11Activity extends ActionBarActivity {
private ArrayList<RadioGroup> radioGroupArrayList;
private String inspectorId;
private String siteName;
private String siteAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity11);
setFields();
setUI();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_activity11, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setFields() {
Intent intentBundle = getIntent(); // get intent
Bundle bundle = intentBundle.getExtras(); // get bundle from intent
inspectorId = bundle.getString(MainActivity.INSPECTORID);
siteName = bundle.getString(MainActivity.SITENAME);
siteAddress = bundle.getString(MainActivity.SITEADDRESS);
}
private void setUI() {
TextView textView;
radioGroupArrayList = new ArrayList<RadioGroup>();
LinearLayout ll = (LinearLayout) this.findViewById(R.id.layout);
int count = 0;
for(int i = 0; i<6; i++){
int id = getResources().getIdentifier("PreStart"+ i, "array" , getPackageName());
String [] questions = getResources().getStringArray(id);
textView = new TextView(this);
textView.setText(questions[0]);
textView.setTextSize(24);
textView.setTypeface(null, Typeface.BOLD);
ll.addView(textView);
TextView textView1;
TextView textView2;
RadioGroup radioGroup;
RadioButton radioButton1;
RadioButton radioButton2;
RadioButton radioButton3;
for (int j = 1; j< questions.length; j++){
textView1 = new TextView(this);
textView1.setText(questions[j]);
textView1.setTextSize(18);
radioGroup = new RadioGroup(this);
radioGroupArrayList.add(radioGroup);
radioButton1 = new RadioButton(this);
radioButton2 = new RadioButton(this);
radioButton3 = new RadioButton(this);
radioButton1.setText("Yes");
radioButton2.setText("No");
radioButton3.setText("NA");
radioButton1.setId(count);
radioButton2.setId(count+1);
radioButton3.setId(count+2);
count = count + 3;
radioGroup.addView(radioButton1);
radioGroup.addView(radioButton2);
radioGroup.addView(radioButton3);
radioButton1.setPadding(20, 20, 100, 20);
radioButton2.setPadding(20, 20, 100, 20);
radioButton3.setPadding(20, 20, 100, 20);
radioGroup.setOrientation(LinearLayout.HORIZONTAL);
textView2 = new TextView(this);
textView2.setVisibility(View.INVISIBLE);
ll.addView(textView1);
ll.addView(radioGroup);
ll.addView(textView2);
}
}
EditText editText = new EditText(this);
editText.setId(R.id.editText11);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("Enter Comments Here");
ll.addView(editText);
}
public void save(View view){
AnswerListCreator answerCreator = new AnswerListCreator(radioGroupArrayList);
String[] answerList = answerCreator.getAnswerList();
String commentLog = ((EditText) findViewById(R.id.editText11)).getText().toString();
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Site site = new Site(inspectorId, siteName, siteAddress, answerList, commentLog, 0);
dbHelper.insertSite(db, site);
// go back to main
Intent intent = new Intent(this, MainActivity.class);
setContentView(R.layout.activity_main);
startActivity(intent);
db.close();
finish();
}
public void submit(View view) {
AnswerListCreator answerCreator = new AnswerListCreator(radioGroupArrayList);
if (!answerCreator.isComplete()) {
com.ammar.android.dailyjobsiteinspection2.Message.message(this, "All fields must be checked");
} else {
answerCreator = new AnswerListCreator(radioGroupArrayList);
String[] answerList = answerCreator.getAnswerList();
String commentLog = ((EditText) findViewById(R.id.editText11)).getText().toString();
DBHelper dbHelper = new DBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Site site = new Site(inspectorId, siteName, siteAddress, answerList, commentLog, 1);
dbHelper.insertSite(db, site);
// go back to main
Intent intent = new Intent(this, MainActivity.class);
setContentView(R.layout.activity_main);
startActivity(intent);
db.close();
finish();
}
}
}
You are changing first Activity's View before calling StartActivity.
Remove this in MainActivity1Activity:
setContentView(R.layout.activity_main_activity11);
Furthermore, if you want to keep view state in MainActivity1Activity don't start it again. Just call finish() in second activity.
Related
I started to develop an app for my final year project. I created all the navigation drawers with no issue and they worked fine when I had run the program. When I added a search-page that would link in with the mapsAcivity I added. No errors are appearing however the app will run fine but when I click on the navigation drawer to access the search page and mapsActivity page the app crashes. Any ideas what the issue is?Screengrab of the app failing
04-26 23:48:25.311: E/AndroidRuntime(13703): Caused by: android.view.InflateException: Binary XML file line #285: ScrollView can host only one direct child
04-26 23:48:25.311: E/AndroidRuntime(13703): Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child
Below is the code for my search screen
package com.example.mcdai.derrytourism;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SearchScreen extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Spinner restaurantSpinner, accommidationSpinner;
ArrayAdapter<CharSequence> adapter;
Button btnSearch;
TextView buttonLogout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
final EditText freeTextEntry = (EditText)findViewById(R.id.editFreeTextSearch);
//final EditText editMinDestination = (EditText)findViewById(R.id.editMinDestination);
final EditText editMaxDestination = (EditText)findViewById(R.id.editMaxDestination);
final EditText editMinPrice = (EditText)findViewById(R.id.editMinPrice);
final EditText editMaxPrice = (EditText)findViewById(R.id.editMaxPrice);
final Spinner spinnerRestautantType = (Spinner)findViewById(R.id.spinnerRestaurantType);
final Spinner spinnerAccommidationType = (Spinner)findViewById(R.id. spinnerAccommidationType);
buttonLogout = (TextView)findViewById(R.id.buttonLogout);
editMinPrice.setEnabled(false);
editMaxPrice.setEnabled(false);
spinnerRestautantType.setEnabled(false);
spinnerAccommidationType.setEnabled(false);
//restaurant drop down menu
restaurantSpinner = (Spinner)findViewById(R.id.spinnerRestaurantType);
adapter = ArrayAdapter.createFromResource(this,R.array.restaurant_type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
restaurantSpinner.setAdapter(adapter);
restaurantSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
TextView defaultPleaseSelect = (TextView) view;
if(position == 0)
{
// Set hint size and colour
defaultPleaseSelect.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
defaultPleaseSelect.setTextColor(Color.GRAY);
}
else
{
// Set dropdown selection and display an onscreen message
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+" selected", Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
//Accommidation drop down menu
accommidationSpinner = (Spinner)findViewById(R.id.spinnerAccommidationType );
adapter = ArrayAdapter.createFromResource(this,R.array.accommidation, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
accommidationSpinner.setAdapter(adapter);
accommidationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
TextView defaultPleaseSelect = (TextView) view;
if(position == 0)
{
// Set hint size and colour
defaultPleaseSelect.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
defaultPleaseSelect.setTextColor(Color.GRAY);
}
else
{
// Set dropdown selection and display an onscreen message
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+" selected", Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
btnSearch = (Button)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intentMapsActivity = new Intent(SearchScreen.this, MapsActivity.class);
//code to get min desitance for destination
//String minDestination = editMinDestination.getText().toString().trim();
//code to get max distance for destination
if(editMaxDestination.getText().toString().equals(""))
{
Toast.makeText(SearchScreen.this, "Please Populate Distance Field", Toast.LENGTH_LONG).show();
}
else
{
Double maxDestination = Double.parseDouble(editMaxDestination.getText().toString());
//code to get from editTextFreeSearch
String freeTextSearchParam = freeTextEntry.getText().toString();
//code to get restaurant type spinner
String restaurantTypeSpinner = spinnerRestautantType.getSelectedItem().toString();
//code to get accommidation type spinner
String accommidationSpinner = spinnerAccommidationType .getSelectedItem().toString();
if(freeTextSearchParam.equals("") && restaurantTypeSpinner.equals("Select") && accommidationSpinner.equals("Select"))
{
Toast.makeText(SearchScreen.this, "Please Populate Free Text, Price or Restaurant Type", Toast.LENGTH_LONG).show();
}
else
{
freeTextSearchParam = freeTextSearchParam.replaceAll("\\s", "\\+");
intentMapsActivity.putExtra("freeTextSearch", freeTextSearchParam);
intentMapsActivity.putExtra("maxDestination", maxDestination);
restaurantTypeSpinner = restaurantTypeSpinner.replaceAll("\\s", "\\+");
intentMapsActivity.putExtra("restaurantType", restaurantTypeSpinner);
accommidationSpinner = accommidationSpinner.replaceAll("\\s", "\\+");
intentMapsActivity.putExtra("accommidation", accommidationSpinner);
startActivity(intentMapsActivity);
}
}
}
});
buttonLogout = (TextView)findViewById(R.id.buttonLogout);
buttonLogout.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(), SearchScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}
public void onRadioButtonClicked(View view)
{
//EditText editMinDestination = (EditText)findViewById(R.id.editMinDestination);
EditText editMaxDestination = (EditText)findViewById(R.id.editMaxDestination);
EditText editMinPrice = (EditText)findViewById(R.id.editMinPrice);
EditText editMaxPrice = (EditText)findViewById(R.id.editMaxPrice);
Spinner spinnerRestautantType = (Spinner)findViewById(R.id.spinnerRestaurantType);
Spinner spinnerAccommidationType = (Spinner)findViewById(R.id.spinnerAccommidationType );
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
boolean unchecked = !((RadioButton) view).isChecked();
switch(view.getId())
{
case R.id.radioPrice:
if (checked)
{
editMinPrice.setEnabled(true);
editMaxPrice.setEnabled(true);
}break;
case R.id.radioRestuarantType:
if (checked)
{
spinnerRestautantType.setEnabled(true);
} break;
case R.id.radioAccommidationType:
if (checked)
{
spinnerAccommidationType.setEnabled(true);
}break;
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_MainActivity) {
Intent intentMainActivity = new Intent(SearchScreen.this, MainActivity.class);
startActivity(intentMainActivity);
finish();
} else if (id == R.id.nav_SearchScreen) {
Intent intentSearchScreen = new Intent(SearchScreen.this,SearchScreen.class);
startActivity(intentSearchScreen);
finish();
} else if (id == R.id.nav_Attractions) {
Intent intentAttractions = new Intent(SearchScreen.this, Attractions.class);
startActivity(intentAttractions);
finish();
} else if (id == R.id.nav_Food) {
Intent intentFood = new Intent(SearchScreen.this, Food.class);
startActivity(intentFood);
finish();
} else if (id == R.id.nav_Accommidation) {
Intent intentAccommidation = new Intent(SearchScreen.this,Accommidation.class);
startActivity(intentAccommidation);
finish();
} else if (id == R.id.nav_Entertainment) {
Intent intentEntertainment = new Intent(SearchScreen.this,Entertainment.class);
startActivity(intentEntertainment);
finish();
} else if (id == R.id.nav_MapsActivity) {
Intent intentMapsActivity = new Intent(SearchScreen.this,MapsActivity.class);
startActivity(intentMapsActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Code below was taken from activity_search_screen.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<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="com.example.mcdai.derrytourism.SearchScreen">
<TextView
android:id="#+id/txtSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:paddingBottom="50sp"
android:textAlignment="center"
android:textSize="20sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/txtFreeTextSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Free-Text Search"
android:textStyle="bold"
android:textAlignment="center"
android:textSize="20sp"
android:paddingBottom="20sp"
android:textAppearance="#style/TextAppearance.AppCompat"
android:layout_below="#+id/txtSearch"
android:layout_alignParentLeft="true" />
<Button
android:id="#+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_alignTop="#+id/txtAccommidationType"
android:layout_toRightOf="#+id/txtDestination"
android:layout_centerHorizontal="true"
android:layout_marginTop="50sp" />
<TextView
android:id="#+id/txtAccommidationType"
android:text="AccommidationType"
android:textSize="15sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:layout_marginLeft="40dp"
android:layout_alignBottom="#+id/radioGroup"
android:layout_toRightOf="#+id/radioGroup"
android:paddingBottom="10sp" />
<EditText
android:id="#+id/editFreeTextSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:ems="10"
android:inputType="text"
android:layout_below="#+id/txtFreeTextSearch"
android:layout_centerHorizontal="true" />
<Spinner
android:id="#+id/spinnerAccommidationType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/txtAccommidationType"
android:layout_alignParentRight="true" />
<Spinner
android:id="#+id/spinnerRestaurantType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txtRestuarantType"
android:layout_alignParentRight="true"
android:layout_alignLeft="#+id/spinnerAccommidationType" />
<TextView
android:id = "#+id/buttonLogout"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:text = "Logout"
android:textSize="15sp"
android:textAlignment="center"
android:clickable="false"
android:textColor="#android:color/holo_blue_dark"
android:onClick="onClick"
android:paddingBottom="50sp"
android:layout_alignBaseline="#+id/txtSearch"
android:layout_alignBottom="#+id/txtSearch"
android:layout_alignParentRight="true" />
<TextView
android:id="#+id/txtMaxPrice"
android:text="Max(£)"
android:textSize="10sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textAlignment="center"
android:layout_above="#+id/editMinPrice"
android:layout_alignParentRight="true"
android:layout_alignLeft="#+id/editMaxPrice"
android:layout_marginBottom="-4sp" />
<EditText
android:id="#+id/editMaxPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:hint="10"
android:textSize="15sp"
android:textAlignment="center"
android:background="#android:color/transparent"
android:inputType="numberDecimal"
android:layout_marginBottom="21dp"
android:layout_above="#+id/spinnerRestaurantType"
android:layout_alignParentRight="true" />
<TextView
android:id="#+id/txtMinPrice"
android:text="Min(£)"
android:textSize="10sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textAlignment="center"
android:layout_above="#+id/editMinPrice"
android:layout_alignLeft="#+id/editMinPrice"
android:layout_toLeftOf="#+id/txtMaxPrice"
android:layout_marginBottom="-4sp"
android:paddingRight="55sp" />
<EditText
android:id="#+id/editMaxDestination"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:hint="10"
android:textSize="15sp"
android:background="#android:color/transparent"
android:textAlignment="center"
android:inputType="number"
android:layout_below="#+id/txtDestination"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/txtCriteriaSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Criteria Search"
android:textStyle="bold"
android:textAlignment="center"
android:textSize="20sp"
android:paddingTop="20sp"
android:textAppearance="#style/TextAppearance.AppCompat"
android:paddingBottom="10sp"
android:layout_marginTop="41dp"
android:layout_below="#+id/editFreeTextSearch"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/txtDestination"
android:text="Max Distance (km)"
android:textSize="15sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:layout_below="#+id/editFreeTextSearch"
android:layout_centerHorizontal="true"
android:paddingTop="10sp" />
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="14sp"
android:paddingBottom="6sp"
android:layout_below="#+id/txtCriteriaSearch"
android:layout_alignParentLeft="true">
<RadioButton
android:id="#+id/radioPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:layout_marginTop="10sp"
android:layout_marginBottom="3sp" />
<RadioButton
android:id="#+id/radioRestuarantType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:layout_marginTop="10sp"/>
<RadioButton
android:id="#+id/radioAccommidationType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioRestuarantType"
android:onClick="onRadioButtonClicked"
android:layout_marginTop="15sp" />
</RadioGroup>
<EditText
android:id="#+id/editMinPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:hint="0"
android:textSize="15sp"
android:textAlignment="center"
android:background="#android:color/transparent"
android:inputType="numberDecimal"
android:layout_alignBaseline="#+id/editMaxPrice"
android:layout_alignBottom="#+id/editMaxPrice"
android:layout_toLeftOf="#+id/buttonLogout"
android:paddingRight="55sp" />
<TextView
android:id="#+id/txtPrice"
android:text="Price"
android:textSize="15sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:paddingTop="7sp"
android:layout_alignTop="#+id/txtMaxPrice"
android:layout_alignLeft="#+id/txtRestuarantType" />
<TextView
android:id="#+id/txtRestuarantType"
android:text="Restuarant Type"
android:textSize="15sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:layout_marginBottom="26dp"
android:paddingBottom="2sp"
android:layout_above="#+id/txtAccommidationType"
android:layout_alignLeft="#+id/txtAccommidationType"
android:layout_alignStart="#+id/txtAccommidationType" />
</RelativeLayout>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_search_screen"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_search_screen"
app:menu="#menu/activity_search_screen_drawer" />
</android.support.v4.widget.DrawerLayout>
</ScrollView>
The reason you're crashing is your ScrollView has more than one child element in it. You'll need to either wrap them both in a parent view sitting inside the ScrollView or move your DrawerLayout outside of the ScrollView.
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<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="com.example.mcdai.derrytourism.SearchScreen">
<!-- RelativeLayout Children go here -->
</RelativeLayout>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_search_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_search_screen"
app:menu="#menu/activity_search_screen_drawer"/>
</android.support.v4.widget.DrawerLayout>
</FrameLayout>
</ScrollView>
I'm not sure exactly what you want your layout to look like but if you follow the above you shouldn't be crashing. Make sure you are using Code > Reformat Code to keep your indentations consistent. Good luck!
So I have 2 edittext fields which to me look the same in my android project.
They are both for decimals.
However the KM one keeps bringing up a keyboard with the option of entering letters and doesn't let me close the keyboard.
The Miles one opens up a number only keyboard and has a checkmark which lets me close the keyboard.
Wondering if something in the code is making this happen
I have added images below
package a00891437.set3s.comp3975.convertunits;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioGroup;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onRadioButtonClicked(final View view){
EditText mText = (EditText) findViewById(R.id.MilesText);
EditText kmText = (EditText) findViewById(R.id.KilometersText);
mText.setText("");
kmText.setText("");
if(view.getId()== R.id.KmToMButton) {
mText.setEnabled(false);
kmText.setEnabled(true);
}
if(view.getId() == R.id.MToKmButton){
kmText.setEnabled(false);
mText.setEnabled(true);
}
}
public void onClickedText (final View view){
EditText kilometers = (EditText) findViewById(R.id.KilometersText);
EditText miles = (EditText) findViewById(R.id.MilesText);
double km= 0;
double m = 0;
if(kilometers.isEnabled() == true){
km = Double.parseDouble(kilometers.getText().toString());
m = km * 0.621371;
miles.setText(Double.toString(m));
}
if(miles.isEnabled() == true){
m = Double.parseDouble(miles.getText().toString());
km = m * 1.60934;
kilometers.setText(Double.toString(km));
}
}
}
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:id="#+id/screen">
TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="110dp"
android:onClick="onClickedText"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/KilometersText"
android:layout_above="#+id/button"
android:layout_marginBottom="134dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:enabled="false"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/MilesText"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/KilometersText"
android:layout_alignStart="#+id/KilometersText"
android:enabled="false"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Km"
android:id="#+id/Kilometers"
android:layout_alignTop="#+id/KilometersText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="43dp"
android:layout_marginStart="43dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="M"
android:id="#+id/Miles"
android:layout_alignTop="#+id/MilesText"
android:layout_alignRight="#+id/Kilometers"
android:layout_alignEnd="#+id/Kilometers" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/radio_group">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kilometers to Miles"
android:id="#+id/KmToMButton"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/MToKmButton"
android:layout_alignStart="#+id/MToKmButton"
android:checked="false"
android:onClick="onRadioButtonClicked"/>/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Miles to Kilometers"
android:id="#+id/MToKmButton"
android:layout_below="#+id/KmToMButton"
android:layout_alignLeft="#+id/Kilometers"
android:layout_alignStart="#+id/Kilometers"
android:checked="false"
android:onClick="onRadioButtonClicked"/>/>
</RadioGroup>
</RelativeLayout>
Also had this problem once where the EditTexts didn't seem to listen to the XML. this fixed it for me:
kmText.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
im tired to try this thing,can help me find out my solution.
I try to validate Edittext if edittext filed empty when i push a button will show a toast message.
this my layout.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MyActivity"
android:id="#+id/relativeLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Panjang"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="right|left" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="20"
android:id="#+id/editTextPanjang"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:maxLength="10"
android:hint="Panjang"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lebar"
android:id="#+id/textView2"
android:layout_below="#+id/editTextPanjang"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="right|left"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="20"
android:id="#+id/editTextLebar"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:maxLength="10"
android:hint="Lebar"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hitung Luas"
android:id="#+id/buttonHitungLuas"
android:layout_below="#+id/editTextLebar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="hitugLuas"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Luas"
android:id="#+id/textView3"
android:layout_below="#id/buttonHitungLuas"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="20"
android:id="#+id/editTextLuas"
android:layout_below="#id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextLuas"
android:id="#+id/buttonClear"
android:text="#string/btn_clear"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/buttonClear"
android:layout_below="#+id/editTextLuas"
android:id="#+id/buttonExit"
android:text="Exit"
/>
</RelativeLayout>
this my java
package com.example.aan.myfirstapp;
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MyActivity extends ActionBarActivity {
private EditText edtPanjang;
private EditText edtLebar;
private EditText edtLuas;
private Button btnHitungLuas;
private Button btnClear;
private Button btnExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
initUI();
initEvent();
}
private void initUI(){
edtPanjang = (EditText) findViewById(R.id.editTextPanjang);
edtLebar = (EditText) findViewById(R.id.editTextLebar);
edtLuas = (EditText) findViewById(R.id.editTextLuas);
btnHitungLuas = (Button) findViewById(R.id.buttonHitungLuas);
btnClear = (Button) findViewById(R.id.buttonClear);
btnExit = (Button) findViewById(R.id.buttonExit);
}
private void initEvent() {
btnHitungLuas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hitungLuas();
}
}
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clearData();
}
});
btnExit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View paramView) {
MyActivity.this.finish();
}
});
}
private void hitungLuas(){
int panjang = Integer.parseInt(edtPanjang.getText().toString());
int lebar = Integer.parseInt(edtLebar.getText().toString());
int luas = panjang*lebar;
edtLuas.setText(luas+"");
}
private void clearData(){
edtLuas.setText("");
edtLebar.setText("");
edtPanjang.setText("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Sory for my bad english
log chat when i run the emulator
03-12 09:29:21.784 1710-2323/com.google.process.gapps E/Backup﹕ [LegacyBackupAccountManager] Fail to get legacy transport context.
android.content.pm.PackageManager$NameNotFoundException: Application package com.google.android.backup not found
at android.app.ContextImpl.createPackageContextAsUser(ContextImpl.java:2139)
at android.app.ContextImpl.createPackageContext(ContextImpl.java:2115)
at android.content.ContextWrapper.createPackageContext(ContextWrapper.java:658)
at com.google.android.gms.backup.am.<init>(SourceFile:47)
at com.google.android.gms.backup.a.a(SourceFile:65)
at com.google.android.gms.backup.c.a(SourceFile:39)
at com.google.android.gms.backup.b.a(SourceFile:67)
at com.google.android.gms.backup.b.a(SourceFile:39)
at com.google.android.gms.backup.BackupAccountNotifierService.onHandleIntent(SourceFile:76)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
You need to handle onClick of the button in this manner and show a toast if the edittext is empty
if(editText.getText().toString().trim().length()==0){
Toast.makeText(getApplicationContext(), "field is empty",
Toast.LENGTH_LONG).show();
}else{
//your code here
}
If you want to check for empty EditText.. try TextUtils for it.
Example
if (TextUtils.isEmpty(edtText.getText().toString().trim())) {
Toast.makeText(getBaseContext(),
"Empty", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getBaseContext(),
"Not Empty", Toast.LENGTH_SHORT)
.show();
}
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 8 years ago.
Here is my code and something i am in need is to use EditText as my output,i have no errors but after the main activity is loaded it say unfortunately myapp has stopped working.
Here is my MainActivity.java code::
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements android.view.View.OnClickListener{
Button b1,b2;
EditText t1,t2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
t1 = (EditText) findViewById(R.id.editText2);
}
public void onClick(View v) {
float b;
if(v.getId()==R.id.button1){
float a = Float.valueOf(t1.getText().toString());
b=a*1024;
t2.setText(" "+b,TextView.BufferType.EDITABLE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
xml code:
<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.techbolt.byteconverter.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:text="#string/hello_world" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="#string/bit" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text="#string/button" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="#string/bytes" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/textView2"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="#string/bytes" />
</RelativeLayout>
You forgot to initialize your t2 variable. Please add below line:
t1 = (EditText) findViewById(R.id.editText1);
t2 = (EditText) findViewById(R.id.editText2);
Try to change
public void onClick(View v) {
float b;
if(v.getId()==R.id.button1){
float a = Float.valueOf(t1.getText().toString());
b=a*1024;
t2.setText(" "+b,TextView.BufferType.EDITABLE);
}
}
Via
public void onClick(View v) {
double b;
if(v.getId()==R.id.button1){
double e1 = Double.parseDouble(t1.getText().toString());
b=a*1024;
t2.setText(" "+String.valueOf(b),TextView.BufferType.EDITABLE);
}
}
and add
t1 = (EditText) findViewById(R.id.editText1);
t2 = (EditText) findViewById(R.id.editText2);
I get an error when I run my android app on my android device. It says Unfortunately, GuessingGame has stopped. It was running before but ever since I added a EditText to the layout, it has been crashing. Here is my MainActivity.java:
package com.h2ogaming.numberguessinggame;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.textView1);
Button pressMe = (Button) findViewById(R.id.button1);
pressMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randText = "";
// TODO Auto-generated method stub
Random randGen = new Random();
int random = randGen.nextInt(5) + 1;
randText = Integer.toString(random);
textOne.setText(randText);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here is my Activity_Main XML file:
<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=".MainActivity"
android:background="#2288ee">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="79dp"
android:text="#string/guess_text"
android:textColor="#ffffff"
android:textSize="26sp" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="#string/text_view1"
android:textColor="#ffffff"
android:textSize="26sp" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="#string/btn_press" />
</RelativeLayout>
Please help me. Thanks!
Change your initialization for components.declare proper all components globally. then initialize it like below code:
public class MainActivity extends Activity {
TextView textOne;
Button pressMe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textOne = (TextView) findViewById(R.id.textView1);
pressMe = (Button) findViewById(R.id.button1);