Cannot get a reference to EditText using 'findViewById()' after 'setContentView()' - java

In an activity where the user is supposed to enter his credentials, in the 'onCreate(...)' of activity, after setContentView(layout) I am doing this:
nameView = (EditText) findViewById(R.id.profileNameTextBox);
Where nameView is an EditText. When I try to get the text from this variable on a button click, my application crashes. The reason behind it is that nameView holds a null object reference. I can't really understand the reason behind because the function 'findViewById(...)' returns a valid reference to every other View object like Button, Spinner, Image but returns null when called for EditText. I have rechecked the ids multiple times and cross checked almost every little dependency, googled a lot but can't really find the solution, or the cause of the problem.
Bottom line is that the function findViewById is returning null to an object which clearly exists in the layout file with the same id used for the search.
Any help regarding this is appreciated.
This is my Activity
package theappman.speedcontacts;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddContact extends AppCompatActivity {
Contact currentContact;
private EditText nameView;
private EditText numberView;
private ImageView imageView;
private Spinner dayView;
private Spinner monthView;
private Spinner yearView;
private Button saveView;
private void loadViews(){
numberView = (EditText) findViewById(R.id.profileNumberTextBox);
imageView = (ImageView) findViewById(R.id.profileImage);
dayView = (Spinner) findViewById(R.id.dateSpinner);
monthView = (Spinner) findViewById(R.id.monthSpinner);
yearView = (Spinner) findViewById(R.id.yearSpinner);
saveView = (Button) findViewById(R.id.saveButton);
nameView = (EditText) findViewById(R.id.profileNameTextBox);
}
private void populateSpinners(){
String[] days = new String[32];
String[] months = new String[13];
String[] years = new String[71];
days[0] = "Day";
months[0] = "Month";
years[0] = "Year";
for (int i=1; i<32; i++){
days[i] = String.valueOf(i+1);
}
for (int i=1,j=69; i<71; i++,j--){
years[i] = String.valueOf(1947+j);
}
months[1] = "January";
months[2] = "February";
months[3] = "March";
months[4] = "April";
months[5] = "May";
months[6] = "June";
months[7] = "July";
months[8] = "August";
months[9] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";
ArrayAdapter<String> dayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, days);
dayView.setAdapter(dayAdapter);
ArrayAdapter<String> monthAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, months);
monthView.setAdapter(monthAdapter);
ArrayAdapter<String> yearAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, years);
yearView.setAdapter(yearAdapter );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
currentContact = new Contact();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
}
});
loadViews();
populateSpinners();
saveView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (nameView != null) {
String nnn = nameView.getText().toString();
Toast.makeText(AddContact.this, nnn,Toast.LENGTH_LONG).show();
}
Toast.makeText(AddContact.this, "not.",Toast.LENGTH_LONG).show();
}
});
}
public void saveContact(View view){
EditText t = (EditText) view.findViewById(R.id.profileNameTextBox);
String NAME = t.getText().toString();
//String NUMBER = view.findViewById(R.id.profileNumber).toString();
Toast.makeText(AddContact.this, "Ok.",Toast.LENGTH_LONG).show();
/*String DATE = day.getSelectedItem().toString() + "-" + month.getSelectedItem().toString() + "-" + year.getSelectedItem().toString();
if (NAME.equals("") || NUMBER.equals("") ){//|| day.getSelectedItem().toString().equals("Day") || month.getSelectedItem().toString().equals("Month") || year.getSelectedItem().toString().equals("Year")){
Toast.makeText(this, "Please fill all fields.",Toast.LENGTH_LONG).show();
return;
}*/
//currentContact.setName(NAME);
//currentContact.setNumber(NUMBER);
//currentContact.setDateOfBirth(DATE );
//save currentContact in database
/*Intent intent = getIntent();
intent.putExtra("key", "Contact Saved");
setResult(RESULT_OK, intent);
finish();*/
}
#Override
public void onBackPressed() {
nameView = (EditText) findViewById(R.id.profileNameTextBox);
Intent intent = getIntent();
intent.putExtra("key", nameView.getText().toString());
setResult(RESULT_OK, intent);
finish();
super.onBackPressed();
}
}
These are my layout files
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="theappman.speedcontacts.AddContact">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_add_contact" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
The above file includes the code given below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="theappman.speedcontacts.AddContact"
tools:showIn="#layout/activity_add_contact">
<ImageView
android:id="#+id/profileImage"
android:src="#drawable/ic_person_black_48dp"
android:layout_width="match_parent"
android:layout_height="200dp" />
<Button
android:id="#+id/selectImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Select Picture"
/>
<EditText
android:name="#+id/profileNameTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Full Name"/>
<EditText
android:name="#+id/profileNumberTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:hint="Enter Phone Number"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:orientation="horizontal"
android:weightSum="3"
>
<Spinner
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:id="#+id/dateSpinner"
/>
<Spinner
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:id="#+id/monthSpinner"/>
<Spinner
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:id="#+id/yearSpinner"/>
</LinearLayout>
<Button
android:id="#+id/saveButton"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:text="Save"
android:layout_gravity="right"
/>
</LinearLayout>

You are initializing the profileNameTextBox at multiple places .
At one place you are using -
EditText t = (EditText) view.findViewById(R.id.profileNameTextBox);
to initialize profileNameTextBox.
Remove the initialization from saveContact(), onBackPressed() and from anywhere else.You should initialize it only once in loadViews(). That's it. And when you want to access it you can use nameView.

public void saveContact(View view){
EditText t = (EditText) view.findViewById(R.id.profileNameTextBox);
view is the button clicked. Something tells me that the text box you're looking for is not inside the button.
You created your view variables so you don't have to findViewById all the time. Use them:
EditText t = nameView;

Related

NavigationDrawer blocks/stops other buttons on the activity

I'm creating an app where once you log in, you can click a button and it leads you to a quiz, however, the Profile activity (activity when you first log in) has a navigation drawer and for some reason, the navigation drawer is blocking the use of the buttons on the Profile that leads to the Quiz activity. Does anyone know how to fix this? If there's anything I can do please let me know. I'm sorry if this is a stupid question this is my first time coding an app.
Profile Java:
package com.example.civis;
import android.content.Intent;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.net.Uri;
import android.widget.Button;
public class Profile extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private Button quizbutton;
private Button enrolbutton1;
//Menu Drawer Set Up
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
quizbutton = (Button) findViewById(R.id.quizbutton);
quizbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openQuiz();
}
});
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
// Menu Drawer Navigation
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_profile: // Profile Page Link
Intent i = new Intent(Profile.this, Profile.class);
startActivity(i);
break;
case R.id.nav_current_mps: // Current MP's Link
Intent mpi = new Intent(Profile.this, CurrentMps.class);
startActivity(mpi);
break;
case R.id.nav_local_board: // Local Board Link
Intent locali = new Intent(Profile.this, LocalBoard.class);
startActivity(locali);
break;
case R.id.nav_referendums: // Referendums Link
Intent referendumi = new Intent(Profile.this, Referendums.class);
startActivity(referendumi);
break;
case R.id.nav_elections: // Elections Link
Intent electioni = new Intent(Profile.this, Election.class);
startActivity(electioni);
break;
case R.id.nav_about_us: // About Us Link
Intent aboutusi = new Intent(Profile.this, AboutUs.class);
startActivity(aboutusi);
break;
case R.id.nav_settings: // Settings Link
Intent settingsi = new Intent(Profile.this, Settings.class);
startActivity(settingsi);
break;
case R.id.nav_signout: // Sign Out Link (Links to Sign In Page)
Intent signouti = new Intent(Profile.this, SignIn.class);
startActivity(signouti);
break;
}
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void openQuiz() {
Intent intent = new Intent(this, quiz1.class);
startActivity(intent);
}
}
Profile XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_background"
android:orientation="vertical"
tools:context=".Profile"
tools:openDrawer="start">
<!-- White Card Style Backing -->
<ImageView
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginTop="195dp"
android:background="#drawable/rounded_rectangle_white" />
<!-- Profile Person Image -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_marginTop="90dp"
android:src="#drawable/dp_civis"
tools:ignore="MissingConstraints" />
<!-- Name Area -->
<TextView
android:id="#+id/textView3"
android:layout_width="280dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:background="#drawable/edit_text_style"
android:text="Name"
android:textAlignment="center"
android:textSize="24sp" />
<!-- Political Compass Quiz Button -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/quizbutton"
android:layout_width="280dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginTop="160dp"
android:background="#drawable/edit_purple_button_style"
android:gravity="center"
android:text="Political Compass Quiz"
android:textColor="#FFF"
tools:ignore="MissingConstraints" />
</LinearLayout>
<!-- Enrol to Vote Button -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="visible">
<Button
android:id="#+id/enrolbutton1"
android:layout_width="280dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginTop="320dp"
android:background="#drawable/edit_purple_button_style"
android:gravity="center"
android:text="Enrol to Vote"
android:textColor="#FFF"
tools:ignore="MissingConstraints" />
</LinearLayout>
<!-- Menu Drawer-->
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#00000000"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/navigation_menu" />
</android.support.v4.widget.DrawerLayout>
Quiz Java:
package com.example.civis;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class quiz1 extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtnAgree;
private Button answerBtnDisagree;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT =5;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
// {Question, Choice 1, Choice 2}
{"All firearms should be registered and it should be tougher to get a licence.", "Agree", "Disagree"},
{"16-year-olds are mature enough to make informed decisions so they should be allowed to vote.", "Agree", "Disagree"},
{"It should be compulsory for everyone in New Zealand to be vaccinated against communicable diseases.", "Agree", "Disagree"},
{"We expect too much of NZ’s Police, and some of their work should be done by communities, mental health experts, and social services.", "Agree", "Disagree"},
{"New Zealand’s borders should remain closed to non-citizens until a COVID-19 vaccine is found, even if that takes years.", "Agree", "Disagree"},
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz1);
countLabel = (TextView)findViewById(R.id.countLabel);
questionLabel = (TextView)findViewById(R.id.questionLabel);
answerBtnAgree = (Button)findViewById(R.id.answerBtnAgree);
answerBtnDisagree = (Button)findViewById(R.id.answerBtnDisagree);
// Create quizArray from quizDara
for (int i = 0; i < quizData.length; i++) {
// Prepare array.
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]); // Question
tmpArray.add(quizData[i][1]); // Agree
tmpArray.add(quizData[i][2]); // Disagree
// Add tmpArray to quizArray.
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
// Update quizCountLabel.
countLabel.setText("Q" + quizCount);
// Generate random number between 0 and 1 (quizArray's size -1 )
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
// Pick one quiz set.
ArrayList<String> quiz = quizArray.get(randomNum);
// Set question and right answer.
// Array format: // {Question, Choice 1, Choice 2,}
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
// Remove "Question" from quiz and Shuffle choices
quiz.remove(0);
// Set Choices.
answerBtnAgree.setText(quiz.get(0));
answerBtnDisagree.setText(quiz.get(1));
// Remove this quiz from quizArray.
quizArray.remove(randomNum);
}
public void checkAnswer(View view) {
// Get pushed button.
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if(btnText.equals(rightAnswer)) {
alertTitle = "Thank you for responding";
rightAnswerCount++;
} else {
alertTitle = "Thank you for responding";
}
// Create Dialogue
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Your response has been recorded");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (quizCount == QUIZ_COUNT) {
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();;
}
}
});
builder.setCancelable(false);
builder.show();
}
}
Quiz XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".quiz1"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="#drawable/gradient_background">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/countLabel"
android:text="Q1"
android:textSize="28dp"
android:textColor="#android:color/background_light"
android:layout_marginTop="120dp"/>
<TextView
android:id="#+id/questionLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question"
android:textSize="20dp"
android:layout_gravity="center_horizontal"
android:textColor="#android:color/background_light"
android:layout_marginTop="15dp"/>
<Button
android:id="#+id/answerBtnAgree"
android:layout_width="320dp"
android:layout_height="60dp"
android:layout_marginTop="90dp"
android:text="Agree"
android:background="#drawable/rounded_button"
android:onClick="checkAnswer"/>
<Button
android:id="#+id/answerBtnDisagree"
android:layout_width="320dp"
android:layout_height="60dp"
android:layout_marginTop="40dp"
android:text="Disagree"
android:background="#drawable/rounded_button"
android:onClick="checkAnswer"/>
DrawerLayout should be the parent if you're using NavigationView.
Put the RelativeLayout inside the DrawerLayout.
Your xml should look something like this:
<!-- Menu Drawer-->
<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">
<!-- OTHER VIEWS -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/navigation_menu" />
</android.support.v4.widget.DrawerLayout>

Same Fragment Should Appear one below another according to the Number Selected in Spinner. HOW?

I have a Small Fragment with three EditText and i have a Spinner with 1,2,3 as options in It.
What i want to do is that, when i select '1' from the Spinner, i want my fragment to appear below the spinner in same Activity.
And when i select '2' in Spinner, the same Fragment Should Appear Twice one below another in the same Activity and similarly for when i select '3' from Spinner.
HERE IS THE JAVA CODE
package com.globaltech2u.databaseapp1;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Spinner spinner;
private String bookno[] = {"#","1","2","3","4"};
private ArrayAdapter<String> arrayAdapter;
private EditText editText,editText2,editText3;
private CheckBox checkBox;
private Button button;
private SQLiteDatabase db;
private Database mySQLiteOpenHelper;
private Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.et1);
editText2 = (EditText)findViewById(R.id.et2);
editText3 = (EditText)findViewById(R.id.et3);
checkBox = (CheckBox)findViewById(R.id.cb1);
button = (Button)findViewById(R.id.button);
spinner = (Spinner)findViewById(R.id.booknoselectspinner);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, bookno);
spinner.setAdapter(arrayAdapter);
mySQLiteOpenHelper = new Database(this, "bookrecord", null, 1);
db = mySQLiteOpenHelper.getWritableDatabase();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String bookname = editText.getText().toString();
String bookno = editText2.getText().toString();
String issuedate = editText3.getText().toString();
String query = "insert into bookrecord(bookname,bookno,issuedate) values('"+bookname+"','"+bookno+"','"+issuedate+"')";
Log.e("query",query);
db.execSQL(query);
Toast.makeText(MainActivity.this, "inserted", Toast.LENGTH_SHORT).show();
}
});
final FragmentManager fragmentManager = getFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
for (int j=0;j<=i;j++){
BookentryFragment bookentryFragment = new BookentryFragment();
fragmentTransaction.replace(android.R.id.content, bookentryFragment);
}
fragmentTransaction.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
HERE IS THE MAIN ACTIVITY XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select No. of Books Issued"
android:id="#+id/tv4"
android:layout_centerHorizontal="true"
android:textColor="#color/colorAccent"
android:textSize="19dp"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/booknoselectspinner"
android:layout_toRightOf="#+id/tv4"
>
</Spinner>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/FM1"
android:layout_below="#+id/tv4"
android:orientation="vertical"
>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Record"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/button"
android:layout_below="#+id/FM1"
/>
</RelativeLayout>
HERE IS THE FRAGMENT FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="#drawable/border">
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et1"
android:hint="Enter Book Name"
android:textAlignment="center"
android:layout_centerHorizontal="true"
android:layout_below="#+id/booknoselectspinner"
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et2"
android:hint="Enter Book No."
android:textAlignment="center"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_below="#+id/et1"
android:layout_centerHorizontal="true"
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et3"
android:inputType="date"
android:hint="Select Issue Date"
android:textAlignment="center"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_below="#+id/et2"
android:layout_centerHorizontal="true"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remind me to Return"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:id="#+id/cb1"
android:layout_below="#+id/et3"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
LET ME KNOW IF I SHOULD ATTACH SOMETHING ELSE
I TRIED TO USE WHILE LOOP BUT THE APP CRASHES. PLEASE HELP
THANK YOU
I tried it with this Layout Inflater Code.
FrameLayout item = (FrameLayout) findViewById(R.id.FM1);
View child = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item.addView(child);
It adds the Fragment once when i open the Activity.
But when i select 2 from the spinner, Nothing Happens.
I am using Switch Case for this Purpose
switch (i) {
case 0:
FrameLayout item = (FrameLayout) findViewById(R.id.FM1);
View child = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item.addView(child);
break;
case 1:
FrameLayout item2 = (FrameLayout) findViewById(R.id.FM1);
View child2 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item2.addView(child2);
FrameLayout item3 = (FrameLayout) findViewById(R.id.FM1);
View child3 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item3.addView(child3);
break;
case 2:
FrameLayout item4 = (FrameLayout) findViewById(R.id.FM1);
View child4 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item4.addView(child4);
FrameLayout item5 = (FrameLayout) findViewById(R.id.FM1);
View child5 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item5.addView(child5);
FrameLayout item6 = (FrameLayout) findViewById(R.id.FM1);
View child6 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item6.addView(child6);
break;
}
Make the FrameLayout a class object, and initialize it using (FrameLayout) findViewById(R.id.FM1); only once, outside the switch statement.
In each of your case blocks, add this piece of code in the beginning:
if(item.getChildCount()>0){
item.removeAllViews();
}
EDIT: Your spinner's onItemSelected would be something like:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
item.removeAllViews();
for (int j=0;j<=i;j++){
View v = getLayoutInflater().inflate(R.layout.fragmentXML, null);
item.addView(v);
}
}

How to add strings from editText to a listView

I have a MainActivity with a ListView and an add Button. When the user clicks the add Button it takes you to another activity the CreateActivity for you to enter in data or strings into the editText boxes. After that you click the create Button and it adds the strings to the ListView it shows up, but every time I try to add another item to the ListView it just overrides the first item and doesn't add on to the ListView.
MainActivity.java with listView and add button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
Button addButton;
ListView itemListView;
public static ArrayList<String> arrayList;
public static ArrayAdapter arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle editTextData = getIntent().getExtras();
if(editTextData != null){
itemListView = (ListView)findViewById(R.id.itemListView);
String data = editTextData.getString("data");
arrayList = new ArrayList<String>();
arrayList.add(data);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
if(data != ""){
arrayAdapter.notifyDataSetChanged();
}
}
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivity(intent);
}
});
}
}
activity_main xml with listView and add button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.brian.inventoryapp.MainActivity"
android:weightSum="1">
<Button
android:text="Add"
android:layout_width="wrap_content"
android:layout_height="58dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/addButton" />
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/itemListView"
/>
</RelativeLayout>
CreateActivity.java with four editText boxes and create button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static com.example.brian.inventoryapp.R.id.editTextItem;
public class CreateActivity extends AppCompatActivity {
EditText editTextItem;
EditText editTextModel;
EditText editTextSerial;
EditText editTextID;
Button createButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
getIntent();
editTextItem = (EditText)findViewById(R.id.editTextItem);
editTextModel = (EditText)findViewById(R.id.editTextModel);
editTextSerial = (EditText)findViewById(R.id.editTextSerial);
editTextID = (EditText)findViewById(R.id.editTextID);
createButton = (Button) findViewById(R.id.createButton);
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("data", item);
startActivity(intent);
}
});
}
}
activity_create xml with the four editText boxes and the create button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_create"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.brian.inventoryapp.CreateActivity">
<TextView
android:text="Item Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextItem" />
<TextView
android:text="Model Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:id="#+id/textView2"
android:layout_below="#+id/editTextItem"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextModel" />
<TextView
android:text="Serial Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextModel"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:id="#+id/textView3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextSerial" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher"
android:layout_below="#+id/editTextID"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp"
android:id="#+id/imageButton" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editTextID"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp" />
<TextView
android:text="ID Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/createButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
every time you restart the MainActivity, it is be created, the onCreate method was executed .one method you can use the comment method:use startactivityforResult;
you can read this question how to manage startactivityforResult.the second method is to set MainActivity model to SingleInstance.
You are starting MainActivity over and over again, clearing all data previously loaded.
Try this solution
Main activity:
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
public static final int CREATE_REQUEST = 1;
private Button addButton;
private ListView itemListView;
private ArrayList<String> arrayList;
private ArrayAdapter<String> arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemListView = (ListView) findViewById(R.id.itemListView);
addButton = (Button) findViewById(R.id.addButton);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivityForResult(intent, CREATE_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CREATE_REQUEST) {
if (resultCode == RESULT_OK) {
String item = data.getStringExtra("data");
arrayList.add(item);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
}
}
}
}
In your CreateActivity change createButton listener to this one:
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent();
intent.putExtra("data", item);
setResult(RESULT_OK, intent);
finish();
}
});
Yes it will assume as if the MainActivity is started for the first time so you should use startActivityForResult() method instead of startActivity().This will continue your MainActivity and do not override your list View.

i get the Error: java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification

I don't know what is wrong with this code. I am trying to make a to do list app. I am new to Android and Java programming so please don't get mad if this is a simple errror.It gives me the error in the title.
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" 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">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvItems"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:onClick="onAddItem"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/etNewItem"
android:hint="Enter a new item"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/button"
android:layout_toStartOf="#+id/button" />
</RelativeLayout>
Here is my Java:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//EditText
final EditText etTask = (EditText) findViewById(R.id.etNewItem);
final String Task = etTask.getText().toString();
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
items.add("First Item");
items.add("Second Item");
//Button
Button btn = (Button) findViewById(R.id.button);
//Adding a Task
//OnClickListeners
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.add(etTask.getText().toString());
etTask.setText("");
}
});
}
}
Since you made a change to adapter after ListView was populated, Listview must be informed to repopulate the views with new values by calling notifydatasetchanged() on your adapter ie,
items.add(etTask.getText().toString());
((ArrayAdapter)lvItems.getAdapter()).notifydatasetchanged();
etTask.setText("");

problems with activity layout when back button is pressed

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.

Categories