Reposting this as I initially posted it originally with the wrong title and so it got lost in the void of questions.
I'm creating a small timetable app, and am currently creating a screen with some tabs. Each tab is a seperate fragment and each have 20 edit texts inside of them. What I aim to do, is if the user types in one of the edit texts, then clicks off of it and the focus is lost, to send the text from the edit text field to the main activity. Then, when the confirm button is clicked, any text that is in the edit texts is then saved to an SQLite database.
My problem is that the focus listener doesn't seem to be working.
Here is one of the fragment's code:
package com.example.schoolandrevisiontimetable;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.EditText;
public class Input_slessontime_monday extends Fragment implements OnFocusChangeListener{
OnMondayEditTextChangedListener monCallback;
private String mondayString;
private int mondayPeriod;
private int mondayPosition;
public void MondayEditTextChanged(String mondayEditText, int period, int position){
mondayString = mondayEditText;
mondayPeriod = period;
mondayPosition=position;
monCallback.onMondayEditTextChanged(mondayString, mondayPeriod, mondayPosition);
}
public interface OnMondayEditTextChangedListener {
public void onMondayEditTextChanged(String mondayEditText, int period, int position);
}
EditText[][] mondayInput = new EditText[11][2];
String [][] mondayStrings = new String [11][2];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_input_slessontime_monday,
container, false);
mondayInput[1][0] = (EditText) rootView.findViewById(R.id.mondayslesson1start);
mondayInput[1][1] = (EditText) rootView.findViewById(R.id.mondayslesson1end);
mondayInput[2][0] = (EditText) rootView.findViewById(R.id.mondayslesson2start);
mondayInput[2][1] = (EditText) rootView.findViewById(R.id.mondayslesson2end);
...
//this continues up to 10. Had to delete the rest due to character limitations
Log.v("Monday", "Edit texts all set");
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
monCallback = (OnMondayEditTextChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnMondayEditTextChanged");
}
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
Log.v("monday", "focus change!");
String edittext;
if(!hasFocus)
switch(v.getId()){
case R.id.mondayslesson1start:
edittext = mondayInput[1][0].getText().toString();
MondayEditTextChanged(edittext,1,0);
break;
case R.id.mondayslesson1end:
edittext = mondayInput[1][1].getText().toString();
MondayEditTextChanged(edittext,1,1);
break;
case R.id.mondayslesson2start:
edittext = mondayInput[2][0].getText().toString();
MondayEditTextChanged(edittext,2,0);
break;
case R.id.mondayslesson2end:
edittext = mondayInput[2][1].getText().toString();
MondayEditTextChanged(edittext,2,1);
break;
//this continues up to 10. Had to delete the rest due to character limitations
}
}
}
Here is the activity's code:
package com.example.schoolandrevisiontimetable;
import java.util.List;
import com.astuetz.PagerSlidingTabStrip;
import Database.DatabaseHelper;
import Database.MC_sschoolday;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
/**DETECTIVEREPORT:
* onfocuschange does nothing
* but it seems that getCount() is called everytime you click onto another textbox, or scroll. probably unrelated.
* **/
public class Input_slessontime extends FragmentActivity implements
Input_slessontime_monday.OnMondayEditTextChangedListener,
Input_slessontime_tuesday.OnTuesdayEditTextChangedListener,
Input_slessontime_wednesday.OnWednesdayEditTextChangedListener{
//this class uses the pagerslidingtabstrip library from https://github.com/astuetz/PagerSlidingTabStrip to create a tab layout.
MC_sschoolday[] sday = new MC_sschoolday[7]; //new array of schooldays
int amountOfDays;
List<MC_sschoolday> schoolday;
DatabaseHelper db;
public static FragmentManager fgmanger;
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
Input_slessontime_monday mondayFragment;
String[][][] slessonTimes = new String[8][11][2];
int numberOfLessonTimes=0;
String[] slessonPointer = new String[140];
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v("LessonTimeInput", "oncreate");
db = new DatabaseHelper(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_slessontime);
fgmanger = getSupportFragmentManager();
schoolday = db.getAllSSchoolDays();
amountOfDays = getAmountOfDaysUsed();
tabs = (PagerSlidingTabStrip)findViewById(R.id.tabs); //set the tabs
pager = (ViewPager) findViewById(R.id.pager); //set the pager
adapter = new MyPagerAdapter(fgmanger); //set the adapter
pager.setAdapter(adapter); //set the adapter to the pager
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
db.close();
}
#Override
public void onMondayEditTextChanged(String mondayEditText, int period, int position) {
slessonTimes[1][period][position] = mondayEditText;
Log.v("LessonTimeInput", "MondayLessontime Added "+ period + " " + position);
slessonPointer[numberOfLessonTimes] = ("1"+period+position);
numberOfLessonTimes++;
}
#Override
public void onTuesdayEditTextChanged(String tuesdayEditText, int period,
int position) {
Log.v("LessonTimeInput", "TuesdayLessontime Added "+ period + " " + position);
slessonTimes[2][period][position] = tuesdayEditText;
slessonPointer[numberOfLessonTimes] = ("2"+period+position);
numberOfLessonTimes++;
}
#Override
public void onWednesdayEditTextChanged(String wednesdayEditText, int period,
int position) {
Log.v("LessonTimeInput", "TuesdayLessontime Added "+ period + " " + position);
slessonTimes[3][period][position] = wednesdayEditText;
slessonPointer[numberOfLessonTimes] = ("3"+period+position);
numberOfLessonTimes++;
}
public void confirmslesson(View v){
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.input_slessontime, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
//this gets the amount of days used, so that the code knows how many tabs to generate
public int getAmountOfDaysUsed(){
db = new DatabaseHelper(getApplicationContext()); //open the database
int amountOfDaysUsed=0; //initialise this int
for (int i =0; i<7; i++){
sday[i]=schoolday.get(i); //stores the lessons in an array
}
for (int i =0; i<7; i++){
if(sday[i].getUsed().toString().equals("y")){ //find how many days are used
amountOfDaysUsed++;
}
}
db.close(); //close the database
Log.v("LessonTimeInput", "amount of days used " + amountOfDaysUsed);
return amountOfDaysUsed; //return the int
}
//small subclass for the pageradapter
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
String[] days = new String[7];
db = new DatabaseHelper(getApplicationContext());
int usedCount2=0;
for (int i =0; i< 7; i++){
sday[i]=schoolday.get(i);
if(sday[i].getUsed().toString().equals("y")){
days[usedCount2] = sday[i].getschool_day();
usedCount2++;
}
}
db.close();
Log.v("LessonTimeInput", "getPageTitle");
return days[position];
}
#Override
public int getCount() {
Log.v("LessonTimeInput", "getCount");
return getAmountOfDaysUsed();
}
public Fragment switchFragmentDay(int num) {
DatabaseHelper db;
db = new DatabaseHelper(getApplicationContext());
MC_sschoolday[] sday = new MC_sschoolday[7];
int usedCount1=amountOfDays;
int [] dayID = new int[usedCount1];
int usedCount2=0;
for (int i =0; i< amountOfDays; i++){
sday[i]=schoolday.get(i);
if(sday[i].getUsed().toString().equals("y")){
dayID[usedCount2] = (int) sday[i].getSchool_day_id();
usedCount2++;
}
}
db.close();
switch (dayID[num]){
case 1:
return new Input_slessontime_monday();
case 2:
return new Input_slessontime_tuesday();
case 3:
return new Input_slessontime_wednesday();
case 4:
return new Input_slessontime_thursday();
case 5:
return new Input_slessontime_friday();
case 6:
return new Input_slessontime_saturday();
case 7:
return new Input_slessontime_sunday();
}
return null;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return switchFragmentDay(0);
case 1:
return switchFragmentDay(1);
case 2:
return switchFragmentDay(2);
case 3:
return switchFragmentDay(3);
case 4:
return switchFragmentDay(4);
case 5:
return switchFragmentDay(5);
case 6:
return switchFragmentDay(6);
}
return null;
}
}
public void StartIntent(Class<?> intentclass) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, intentclass);
startActivity(intent);
}
}
The XML for the fragment:
<ScrollView
android:id="#+id/monday_fragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.pipturner.timetable.Input_slessontime_monday"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson1used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson1start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson1used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson1end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson2used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson2used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson2start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson1used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson2end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson2used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson3used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson3start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson3used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson3end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson3used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson4used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson4start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson4used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson4end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson4used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson5used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson5start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson5used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson5end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson5used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson6used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson6start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson6used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson6end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson6used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson7used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson7start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson7used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson7end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson7used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson8used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson8start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson8used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson8end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson8used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="#+id/mondayslesson9used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson9start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson9used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson9end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson9used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/mondayslesson10used"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:text="#string/prompt_lesson" />
<EditText
android:id="#+id/mondayslesson10start"
android:inputType="textMultiLine"
android:hint="#string/start"
android:dependency="mondayslesson10used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
<EditText
android:id="#+id/mondayslesson10end"
android:inputType="textMultiLine"
android:hint="#string/end"
android:dependency="mondayslesson10used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10" />
</LinearLayout>
</LinearLayout>
</ScrollView>
and the XML for the 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:orientation="vertical" >
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="#drawable/background_tabs" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
tools:context=".Input_slessontime" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
style="?android:attr/borderlessButtonStyle"
android:id="#+id/cancelslessontime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/cancel"
android:layout_weight="1" />
<Button
style="?android:attr/borderlessButtonStyle"
android:id="#+id/confirmslessontime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/confirm"
android:layout_weight="1"
android:onClick="confirmslesson" />
</LinearLayout>
</LinearLayout>
Something that may be related, is that when I click on or off an edit text, or scroll the fragment, getCount() is called. Probably unrelated.
Thanks in advance!
needed to set an onFocusListener.
//Thanks for the help guys//
¬¬
Related
I am trying to create an Android app, then has an initial login screen that detects if a user is Admin or User. Once logged in, the user (depending on their role) will see different tabs to swipe between. I have a basic app that starts with a login activity and the login to decipher the users roles (using static values for now). First part is ok. Now when I try to use Fragments after the login screen, I'm getting stuck.
I have a LoginActivity that has an onClikcListener on a button after user enters credentials. Depending on whether the user is Amin or General Users, it will just to a new activity either activity_vote_admin or activity_vote_user. At this point I am stuck. Any ideas if what I am trying to do is valid. Or is there a better way to do this. At the moment I am getting this error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.confidencevotefragmentrebuild/com.example.confidencevotefragmentrebuild.activity_vote_admin}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
LoginActivity (this is my main activity)
...
package com.example.confidencevotefragmentrebuild;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
private static EditText username;
private static EditText password;
public static TextView attempts;
private static Button submit_button;
int attempt_counter = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton();
}
public void loginButton() {
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
attempts = (TextView) findViewById(R.id.textView_Attempts);
//Reference button view
final Button submit_button = findViewById(R.id.submit_button);
// perform click event on button
submit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (username.getText().toString().equals("admin") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, activity_vote_admin.class);
startActivity(intent);
} else if (username.getText().toString().equals("user") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intentUser = new Intent(LoginActivity.this, activity_vote_user.class);
startActivity(intentUser);
} else {
Toast.makeText(LoginActivity.this, "User or Password incorrect",
Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts.setText(Integer.toString(attempt_counter));
if (attempt_counter == 0) {
Toast.makeText(LoginActivity.this, "Too many failed attempts, please close app and try again",
Toast.LENGTH_SHORT).show();
submit_button.setEnabled(false);
}
}
}
}
);
}
}
...
Activity_vote_admin
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
public class activity_vote_admin extends AppCompatActivity {
/**
* Field for selecting the number of confidence votes
*/
RatingBar mResults;
private RatingBar rBar;
Button mBtn;
/**
* Spinner field to enter the project name
*/
private Spinner mProjectSpinner;
/**
* Projects. The possible values are:
* stored locally - Needs to get values from a database. TODO
*/
int mProject = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vote_main_admin);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
AdminFragmentPagerAdapter adapter = new AdminFragmentPagerAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
// initiate a rating bar
rBar = findViewById(R.id.rating_bar);
//float vote = rBar.getRating();
// Find all relevant views for user input
mResults = findViewById(R.id.rating_bar);
mProjectSpinner = findViewById(R.id.spinner_project);
// Run getRating method to get rating number from a rating bar
//getRating();
// Initiate button
mBtn = findViewById(R.id.voteButton);
// perform click event on button
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get values and then displayed in a toast
//String totalStars = "Total Stars:: " + RatingBar.getNumStars();
float vote = rBar.getRating();
String rating = "Rating : " + vote;
Toast.makeText(getApplicationContext(), rating + "\n", Toast.LENGTH_LONG).show();
}
});
projectSpinner();
}
// Setup the dropdown spinner that allows the user to select the role.
private void projectSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
ArrayAdapter projectSpinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.projects, android.R.layout.simple_spinner_item);
// Specify dropdown layout style - simple list view with 1 item per line
projectSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
// Apply the adapter to the project spinner
mProjectSpinner.setAdapter(projectSpinnerAdapter);
// Set the integer mSelected to the constant values
mProjectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if(mProjectSpinner.getSelectedItem() == "This is Hint Text");
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.nextGEMS1_5))) {
mProject = 0 ;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_6))) {
mProject = 1;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_7))) {
mProject = 2;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_8))) {
mProject = 3;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_9))) {
mProject = 4;
return;
}
else mProject = 0;
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mProject = 0; // User
}
});
}
}
...
activity_vote_main_admin.xml
...
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:name="com.example.confidencevotefragmentrebuild.testFragment1"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
...
activity_login.xml
...
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".LoginActivity"
tools:showIn="#layout/activity_login">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/login_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="LOGIN"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/login_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="30dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp">
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/usericon"
android:hint="User Name"
android:inputType="textEmailAddress"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:drawableLeft="#drawable/lock"
android:hint="Password"
android:inputType="textPassword"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:paddingTop="5dp"
android:text="Forgot Password?" />
<Button
android:id="#+id/submit_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Sign in"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="20dp"
android:orientation="horizontal"
android:paddingTop="1dp">
<TextView
android:id="#+id/attempts_text"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="Number of attempts remaining: " />
<TextView
android:id="#+id/textView_Attempts"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="5" />
</LinearLayout>
<TextView
android:id="#+id/lnkRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:gravity="center"
android:paddingTop="30dp"
android:text="Register here"
android:textColor="#5fb0c9"
android:textSize="16sp" />
</LinearLayout>
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="2dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
...
AdminFragemntyPagerAdapter
...
package com.example.confidencevotefragmentrebuild;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class AdminFragmentPagerAdapter extends FragmentPagerAdapter {
public AdminFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new testFragment1();
} else if (position == 1) {
return new testFragment2();
} else {
return new testFragment2();
}
}
#Override
public int getCount() {
return 3;
}
}
...
aactivity_vote_user.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/vote_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="USER VOTE"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/vote_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="70dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<Spinner
android:id="#+id/spinner_project"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:hint="#string/spinner_hint"
android:maxLines="1"
android:singleLine="true"
android:backgroundTint="#color/attCobalt"
android:popupBackground="#color/myBlue"
android:dropDownSelector="#color/attBlue"
/>
</com.google.android.material.textfield.TextInputLayout
>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<RatingBar
android:id="#+id/rating_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stepSize="1.0"
android:layout_marginTop="40dp"
android:theme="#style/rating_bar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="5dp"
android:text="Vote and Submit" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/voteButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Submit"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
/>
</LinearLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
...
My fragments are as follows.
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
public class testFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_vote_user, container, false);
}
}
...
There are two reason for this issue :
You didn't declare any button on "activity_vote_main_admin.xml", thats why your view not binding with activity and giving null pointer exception.
May be you declare the button on fragment xml and trying to bind it with activity.
Trying to load around 500 rows of data in recycler view, but it is lagging while scrolling.
Data doesn't include any kind of images, it is just plain text. Thus could not find any reason of laging.
The xml and java code used is as follows:-
xml
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/markeListCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardPreventCornerOverlap="true"
android:layout_alignParentTop="true"
card_view:cardUseCompatPadding="true"
app:cardCornerRadius="#dimen/_5sdp"
app:cardElevation="#dimen/_5sdp"
android:layout_marginBottom="14dp"
android:paddingBottom="#dimen/_150sdp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="#dimen/_125sdp"
android:background="#drawable/compltedtlist"
android:layout_gravity="center">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="#dimen/_30sdp"
android:layout_marginTop="#dimen/_10sdp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/_5sdp"
android:text="School Name :"
android:singleLine="true"
android:inputType="textPostalAddress"
android:imeOptions="actionNext"
android:textStyle="bold"
android:textSize="#dimen/_10ssp"
android:textColor="#0E9CE0"
android:paddingLeft="#dimen/_10sdp"
android:id="#+id/scndprsnname" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/_10sdp"
android:maxLines="1"
android:text="Divisional Public School"
android:ems="10"
android:singleLine="true"
android:textColor="#000"
android:imeOptions="actionNext"
android:textSize="#dimen/_10ssp"
android:id="#+id/scholnametxt" >
</TextView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_30sdp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/_5sdp"
android:text="District :"
android:singleLine="true"
android:inputType="textPostalAddress"
android:imeOptions="actionNext"
android:textStyle="bold"
android:textSize="#dimen/_10ssp"
android:textColor="#0E9CE0"
android:paddingLeft="#dimen/_10sdp"
android:id="#+id/detaildadresedit" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/_38sdp"
android:maxLines="1"
android:text="Aleem Ahmed"
android:ems="10"
android:singleLine="true"
android:textColor="#000"
android:imeOptions="actionNext"
android:textSize="#dimen/_10ssp"
android:id="#+id/tehsilname" >
</TextView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="#dimen/_30sdp"
android:layout_marginTop="#dimen/_48sdp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/_5sdp"
android:text="Tehsil :"
android:singleLine="true"
android:inputType="textPostalAddress"
android:imeOptions="actionNext"
android:textStyle="bold"
android:textSize="#dimen/_10ssp"
android:textColor="#0E9CE0"
android:paddingLeft="#dimen/_10sdp"
android:id="#+id/pcname" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/_45sdp"
android:maxLines="1"
android:text="Lahore"
android:ems="10"
android:singleLine="true"
android:textColor="#000"
android:imeOptions="actionNext"
android:textSize="#dimen/_10ssp"
android:id="#+id/citytxt" >
</TextView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="#dimen/_30sdp"
android:layout_marginTop="#dimen/_65sdp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="#dimen/_5sdp"
android:text="Address :"
android:textStyle="bold"
android:ems="10"
android:singleLine="true"
android:textColor="#0E9CE0"
android:imeOptions="actionNext"
android:textSize="#dimen/_10ssp"
android:paddingLeft="#dimen/_10sdp"
android:id="#+id/provnceedit" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginRight="#dimen/_10sdp"
android:layout_marginLeft="-40dp"
android:maxLines="1"
android:text="h#10 stret no 17 sabzar lahore"
android:ems="30"
android:singleLine="true"
android:textColor="#000"
android:imeOptions="actionNext"
android:textSize="#dimen/_10ssp"
android:id="#+id/addrestxt" >
</TextView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="#dimen/_50sdp"
android:layout_marginTop="#dimen/_70sdp"
android:layout_gravity="center"
android:paddingTop="#dimen/_10sdp"
android:gravity="center"
android:textAlignment="center"
android:layout_marginLeft="#dimen/_170sdp"
android:layout_marginRight="#dimen/_10sdp"
android:orientation="horizontal">
<Button
android:id="#+id/uploadbtn"
android:layout_width="#dimen/_140sdp"
android:layout_height="#dimen/_30sdp"
android:background="#drawable/yelowbtn"
android:layout_gravity="center"
android:textStyle="bold"
android:textSize="#dimen/_10sdp"
android:textAlignment="center"
android:layout_marginTop="#dimen/_20sdp"
android:layout_marginBottom="#dimen/_15sdp"
android:gravity="center"
android:text="Stage 2"
android:textColor="#000" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
<!--
</LinearLayout>-->
adapter
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.preference.PreferenceManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.offlinemap.R;
import com.offlinemap.form.FormStage2;
import com.offlinemap.form.FormToUpdateData;
import java.util.ArrayList;
import java.util.List;
public class Stage2RecyclerViewAdapterViewCompleteList extends RecyclerView.Adapter<Stage2RecyclerViewAdapterViewCompleteList.SearchViewHolder> {
private Context mCtx;
private List<ModeClassCompleteListStage2> searcList;
View thumb1View;
private String jobid;
private Animator mCurrentAnimator;
private int mShortAnimationDuration;
private modelclascompletelist model;
String job;
private Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
//ImageView image;
private ArrayList<String> list = new ArrayList<String>();
String pos;
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
/*static final int ZOOM = 2;*/
private static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked,scholid,tehsilo ,distrcto ,province ,sgtsID ;
SharedPreferences preferences;
public Stage2RecyclerViewAdapterViewCompleteList(Context mCtx, List<ModeClassCompleteListStage2> searcList)
{
this.mCtx = mCtx;
this.searcList = searcList;
}
#Override
public Stage2RecyclerViewAdapterViewCompleteList.SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.carview_introcomplete, null);
return new Stage2RecyclerViewAdapterViewCompleteList.SearchViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(final Stage2RecyclerViewAdapterViewCompleteList.SearchViewHolder holder, final int position)
{
final ModeClassCompleteListStage2 model = searcList.get(position);
holder.adres.setText(model.getDetailsadres());
holder.scholname.setText(model.getScholname());
holder.district.setText(model.getDistrict());
holder.city.setText(model.getTehsil());
/* Glide.with(mCtx)
.load(model.getImage1())
.into(holder.image);*/
if(model.getStg_id().equals("0")){
holder.edit.setText("Add");
}
else {
holder.edit.setText("Update");
}
holder.edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
/* String mtoid = searcList.get(position).get();*/
scholid = searcList.get(position).getScholid();
tehsilo = searcList.get(position).getTehsil();
distrcto = searcList.get(position).getDistrict();
province = searcList.get(position).getProvince();
sgtsID = searcList.get(position).getStg_id();
preferences = PreferenceManager.getDefaultSharedPreferences(mCtx);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("scholid", scholid);
editor.putString("thsillo", tehsilo);
editor.putString("distrctto", distrcto);
editor.putString("prov", province);
editor.putString("sgts",sgtsID);
editor.apply();
if(holder.edit.getText().toString().equals("Add")) {
Intent intent = new Intent(mCtx.getApplicationContext(), FormStage2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
mCtx.getApplicationContext().startActivity(intent);
}
else {
Intent intent = new Intent(mCtx.getApplicationContext(), FormToUpdateData.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
mCtx.getApplicationContext().startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
/*if (searcList.size() == 0) {
.setVisibility(View.INVISIBLE);
} else {
mRecyclerView.setVisibility(View.VISIBLE);
}*/
return searcList.size();
}
class SearchViewHolder extends RecyclerView.ViewHolder {
/*TextView movingitem, pickup, dropoff,currentbid,date,edit,delete,acceptbid,message,invitetransport,viewquote,similarjob,mesagecount,simlarcount;
ImageView image,largeimage,editimage;
CardView cardView;
ImageView delicon,similaricon,inviteicon,mainimageicon,mesageicon;*/
TextView adres, city, scholname, principalname, secondpersonname, entryno,district;
Button edit;
public SearchViewHolder(View itemView)
{
super(itemView);
adres = itemView.findViewById(R.id.addrestxt);
scholname = itemView.findViewById(R.id.scholnametxt);
edit= itemView.findViewById(R.id.uploadbtn);
district = itemView.findViewById(R.id.tehsilname);
city = itemView.findViewById(R.id.citytxt);
/* movingitem = itemView.findViewById(R.id.MovingItemServlivep);
pickup = itemView.findViewById(R.id.pickupservlivep);
dropoff = itemView.findViewById(R.id.DropOffServlivep);
image = itemView.findViewById(R.id.imagecardlivep);
currentbid = itemView.findViewById(R.id.BidServlivep);
date = itemView.findViewById(R.id.dateservlivep);
edit = itemView.findViewById(R.id.editjob);
delete = itemView.findViewById(R.id.deletejob);
// similarjob = itemView.findViewById(R.id.similarjobtext);
acceptbid = itemView.findViewById(R.id.biddetailslivep);
viewquote = itemView.findViewById(R.id.offerpricelivep);
// invitetransport = itemView.findViewById(R.id.invitetransportertext);
mesagecount = itemView.findViewById(R.id.countermsgs);
// simlarcount = itemView.findViewById(R.id.countersimlar);
editimage= itemView.findViewById(R.id.imageView98);
mesageicon= itemView.findViewById(R.id.imagy98);
delicon= itemView.findViewById(R.id.imagy971);
cardView = itemView.findViewById(R.id.markeListCard);
// similaricon= itemView.findViewById(R.id.imagy981);
// inviteicon= itemView.findViewById(R.id.ima98);
mainimageicon= itemView.findViewById(R.id.imagecardlivep);*/
}
/* public void setFilter(List<UserInfo> newList){
data=new ArrayList<>();
data.addAll(newList);
notifyDataSetChanged();
}*/
}
}
I'm trying to figure out why my app crashes when my AddThreeToTeamA button crashes my application upon clicking. I have addded my XML and my Java code.
I am following a tutorial however it obviously does not crash and I have tried several different solutions.
Any hint will be appreciated.
package com.themovingmonkey.courtcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int score = 0;
int scoreTeamA;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addThreeForTeamA() {
scoreTeamA = score + 3;
displayForTeamA(scoreTeamA);
}
public void addTwoForTeamA() {
scoreTeamA = score + 2;
displayForTeamA(scoreTeamA);
}
public void addOneForTeamA() {
scoreTeamA = score + 1;
displayForTeamA(scoreTeamA);
}
public void displayForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.Team_A_Score);
scoreView.setText(String.valueOf(scoreTeamA));
}
}
////////////////////////////////////////////////////////////////
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text= "Team A"
android:padding="4dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="0"
android:padding="4dp"
android:id="#+id/Team_A_Score"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="3 Points"
android:layout_margin="8dp"
android:onClick="addThreeForTeamA"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2 Points"
android:layout_margin="8dp"
android:onClick="addTwoForTeamA"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1 Point"
android:layout_margin="8dp"
android:onClick="addOneForTeamA"
/>
</LinearLayout>
All methods defined using the android:onClick="someMethod" attribute. Then they have to be public and should pass a View as the only parameter, Change your methods to:
public void someMethod(View view){
//Everything else!
}
Your methods do not pass a View as the only parameter at all currently!
In the Android app I'm developing I'm loading a list of several items for the user to input some data; there's a checkbox and an EditText for each item, and the user can check the checkbox and type some notes regarding the item. This list is loaded dynamically from a local database, which in turn is populated from a remote database at a previous point. Now, the problem I'm having is that, whenever I focus on an EditText, after I lose focus on the element, the list seems to load again (elements which where unchecked/blank originally and had been checked/had text typed in them become unchecked/blank again, and those which were checked/had text initially go back to the original state). This only happens when I lose focus on the EditText; I can check and uncheck the checkboxes and they stay how I leave them (until I get and lose focus on an EditText). How can I avoid this so my elements retain the data?
I've tested the app in deviced with Android versions 3.2 and 4.2
Any help would be appreciated.
Here's the activity that loads the list:
public class PostventaPreentregaDetalleActivity extends Activity implements OnItemClickListener, OnItemSelectedListener {
private ArrayList<EncuestaPostventa> listaChequeoEncuesta;
private ArrayList<ConsumoBien> listaConsumoBien;
private ListView lvChequeoEncuesta;
private ListView lvConsumoBien;
private EncuestaPostventaAdapter adapter;
private ConsumoBienAdapter adapterConsumoBien;
public static DBProvider oDB;
#Override
public void onBackPressed() {
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.postventa_preentrega_detalle_activity_actions, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
getActionBar().setDisplayHomeAsUpEnabled(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_postventa_preentrega_detalle);
listaChequeoEncuesta = new ArrayList<EncuestaPostventa>();
listaConsumoBien = new ArrayList<ConsumoBien>();
inicializarPestanas();
cargarDetalleNegocio();
listarChequeoEncuesta();
listarConsumoBien();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void onItemClick(AdapterView<?> adapter, View view, int position,
long ID) {
}
public void cargarDetalleNegocio(){
Intent intent = getIntent();
TextView tvProyecto;
TextView tvCliente;
TextView tvRut;
TextView tvDireccion;
tvProyecto = (TextView) findViewById(R.id.tvProyecto);
tvRut = (TextView) findViewById(R.id.tvRut);
tvCliente = (TextView) findViewById(R.id.tvCliente);
tvDireccion = (TextView) findViewById(R.id.tvDireccion);
tvProyecto.setText(intent.getStringExtra("proyecto").trim());
tvRut.setText(intent.getStringExtra("rut").trim());
tvCliente.setText(intent.getStringExtra("cliente").trim());
tvDireccion.setText(intent.getStringExtra("direccion").trim());
}
public void inicializarPestanas(){
TabHost tabs = (TabHost)findViewById(android.R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec = tabs.newTabSpec("tabChequeo");
spec.setContent(R.id.tabChequeo);
spec.setIndicator("Chequeo");
tabs.addTab(spec);
spec = tabs.newTabSpec("tabServicios");
spec.setContent(R.id.tabServicios);
spec.setIndicator("Servicios consumidos");
tabs.addTab(spec);
spec = tabs.newTabSpec("tabObservaciones");
spec.setContent(R.id.tabObservaciones);
spec.setIndicator("Observaciones");
tabs.addTab(spec);
tabs.setCurrentTab(0);
}
public void listarChequeoEncuesta(){
try{
oDB = new DBProvider(this);
Intent intent = getIntent();
int idBien = intent.getIntExtra("id_bien", 0);
int idEncuestaPreentrega = intent.getIntExtra("id_encuestapreentrega", 0);
String[][] arrayChequeoEncuesta = oDB.traerEncuestaPostventa(idBien,
idEncuestaPreentrega);
if(!(arrayChequeoEncuesta == null)){
for(int i=0; i<arrayChequeoEncuesta.length; i++){
int idEncuestaPostventa = Integer.parseInt(arrayChequeoEncuesta[i][0]);
int idEncuestaDetalle = Integer.parseInt(arrayChequeoEncuesta[i][1]);
String item = arrayChequeoEncuesta[i][2];
Boolean recepcion = (Integer.parseInt(arrayChequeoEncuesta[i][3]) != 0);
String observacion =arrayChequeoEncuesta[i][4];
listaChequeoEncuesta.add(new EncuestaPostventa(idEncuestaPostventa,
idEncuestaDetalle,
item,
recepcion,
observacion));
}
}
adapter = new EncuestaPostventaAdapter(this, listaChequeoEncuesta);
lvChequeoEncuesta = (ListView) findViewById(R.id.lvChequeoEncuesta);
lvChequeoEncuesta.setAdapter(adapter);
}catch(Exception e){
Toast.makeText(this, "Error (listarChequeoEncuesta): " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void listarConsumoBien(){
try{
oDB = new DBProvider(this);
Intent intent = getIntent();
int argIdBien = intent.getIntExtra("id_bien", 0);
int argIdEmpsa = intent.getIntExtra("id_empsa", 0);
String[][] arrayConsumoBien = oDB.traerConsumoBien(argIdBien,
argIdEmpsa);
if(!(arrayConsumoBien == null)){
for(int i=0; i<arrayConsumoBien.length; i++){
int idConsumoBien = Integer.parseInt(arrayConsumoBien[i][0]);
int idBien = Integer.parseInt(arrayConsumoBien[i][1]);
int idDominio = Integer.parseInt(arrayConsumoBien[i][2]);
String nombre = arrayConsumoBien[i][3];
String unidad = arrayConsumoBien[i][4];
int cantidad = Integer.parseInt(arrayConsumoBien[i][5]);
Boolean estado = (Integer.parseInt(arrayConsumoBien[i][6]) != 0);
listaConsumoBien.add(new ConsumoBien(idConsumoBien,
idBien,
idDominio,
nombre,
unidad,
cantidad,
estado));
}
}
adapterConsumoBien = new ConsumoBienAdapter(this, listaConsumoBien);
lvConsumoBien = (ListView) findViewById(R.id.lvConsumoBien);
lvConsumoBien.setAdapter(adapterConsumoBien);
}catch(Exception e){
Toast.makeText(this, "Error (listarConsumoBien): " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
public void onNothingSelected(AdapterView<?> parent)
{
}
}
And its layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:parentActivityName="net.gestionwireless.officemovil.inmobiliario.PostventaPreentregaActivity">
<TabHost android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelProyecto"
android:text="#string/proyecto"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvProyecto"
android:text=""
android:layout_toRightOf="#id/tvLabelProyecto" />
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelRut"
android:layout_below="#id/tvLabelProyecto"
android:text="#string/rut"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvRut"
android:text=""
android:layout_toRightOf="#id/tvLabelRut"
android:layout_below="#id/tvProyecto" />
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelCliente"
android:layout_marginLeft="50dp"
android:layout_below="#id/tvLabelProyecto"
android:layout_toRightOf="#id/tvRut"
android:text="#string/cliente" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvCliente"
android:text=""
android:layout_toRightOf="#id/tvLabelCliente"
android:layout_below="#id/tvProyecto" />
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvLabelDireccion"
android:layout_below="#id/tvCliente"
android:text="#string/direccion"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/texto_L"
android:id="#+id/tvDireccion"
android:text=""
android:layout_toRightOf="#id/tvLabelDireccion"
android:layout_below="#id/tvCliente" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tvDireccion">
<TabWidget android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#android:id/tabs" />
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/tabcontent">
<LinearLayout
android:id="#+id/tabChequeo"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<TextView
android:text="#string/titulo_grilla_item"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_recepcion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_observacion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".57"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
</LinearLayout>
<ListView
android:id="#+id/lvChequeoEncuesta"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
</ListView>
</LinearLayout>
<LinearLayout
android:id="#+id/tabServicios"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<TextView
android:text="#string/titulo_grilla_servicio"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".4"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_recepcion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_consumo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".3"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
<TextView
android:text="#string/titulo_grilla_unidad"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".2"
android:gravity="center"
android:textSize="#dimen/titulo_grilla"
android:textStyle="bold" />
</LinearLayout>
<ListView
android:id="#+id/lvConsumoBien"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
</ListView>
</LinearLayout>
<LinearLayout android:id="#+id/tabObservaciones"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/etObservaciones"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hint_observaciones" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</RelativeLayout>
</TabHost>
</LinearLayout>
The class for each item:
package net.gestionwireless.officemovil.inmobiliario;
public class EncuestaPostventa {
private int idEncuestaPostventa;
private int idEncuestaDetalle;
private String item;
private Boolean recepcion;
private String observacion;
public EncuestaPostventa(int idEncuestaPostventa,
int idEncuestaDetalle,
String item,
Boolean recepcion,
String observacion) {
this.idEncuestaPostventa = idEncuestaPostventa;
this.idEncuestaDetalle = idEncuestaDetalle;
this.item = item;
this.recepcion = recepcion;
this.observacion = observacion;
}
public int traerIdEncuestaPostventa() {
return idEncuestaPostventa;
}
public void asignarIdEncuestaPostventa(int idEncuestaPostventa) {
this.idEncuestaPostventa = idEncuestaPostventa;
}
public int traerIdEncuestaDetalle() {
return idEncuestaDetalle;
}
public void asignarIdEncuestaDetalle(int idEncuestaDetalle) {
this.idEncuestaDetalle = idEncuestaDetalle;
}
public String traerItem() {
return item;
}
public void asignarItem(String item) {
this.item = item;
}
public Boolean traerRecepcion() {
return recepcion;
}
public void asignarRecepcion(Boolean recepcion) {
this.recepcion = recepcion;
}
public String traerObservacion() {
return observacion;
}
public void asignarObservacion(String observacion) {
this.observacion = observacion;
}
}
package net.gestionwireless.officemovil.inmobiliario;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
The adapter:
public class EncuestaPostventaAdapter extends ArrayAdapter<EncuestaPostventa> {
private Context context;
private ArrayList<EncuestaPostventa> datos;
public EncuestaPostventaAdapter(Context context, ArrayList<EncuestaPostventa> datos) {
super(context, R.layout.encuestapostventa_item, datos);
this.context = context;
this.datos = datos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View item = LayoutInflater.from(context).inflate(
R.layout.encuestapostventa_item, null);
TextView tvItem = (TextView) item.findViewById(R.id.tvItem);
tvItem.setText(datos.get(position).traerItem());
CheckBox chkRecepcion = (CheckBox) item.findViewById(R.id.chkRecepcion);
chkRecepcion.setChecked(datos.get(position).traerRecepcion());
EditText editObservacion = (EditText) item.findViewById(R.id.editObservacion);
editObservacion.setText(datos.get(position).traerObservacion());
return item;
}
}
And the layout for each item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="horizontal">
<TextView
android:id="#+id/tvItem"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".33"
android:textSize="#dimen/texto_L" />
<CheckBox
android:id="#+id/chkRecepcion"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".1"/>
<EditText
android:id="#+id/editObservacion"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".57"
android:textSize="#dimen/texto_L"
android:inputType="textCapSentences" />
</LinearLayout>
If you put a log statement in your ArrayAdapter.getView(), you'll realize what's going on in two seconds.
As the list is scrolled, a list item that you edited is scrolled out of view. When the item is scrolled back into view, the view is recreated and getView() is called. Since your adapter doesn't have a representation of the changes that were made previously, getView() recreates the view with the original unedited data.
If that's happening to you on focus lost, that must mean that the focus-lost event is triggering a view update on the list item. I've never done editing in a list item, so I'm not familiar with that behavior.
You need to put event listeners on your EditText and CheckBox that store their edited state somewhere. Then your adapter needs to use that edit state when creating the list items.
You might have to write a more complex adapter that extends BaseAdapter directly. The adapter is the Model for your list View, and there's no state in a ListView except for your adapter. In the case of ListView, the view can update any part of its list at any time, so the adapter has to have the current model data for the ListView at all times.
Moved from Code Review: https://codereview.stackexchange.com/questions/56123/why-is-my-android-app-showing-up-blank-and-then-crashing
Every time I try to run my Android app, it shows the title bar with no content below it. After two minutes or so, it crashes. Here's the logcat:
http://pastebin.com/UFKeywgC
I know the problem stems from me trying to use a fragment structure for the first time. Here's my code:
TipCalculator.java
/* My verion of the Deitel Tip Calculator */
package org.bh.tipcalculator2;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.NotificationManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TipCalculator extends Activity {
// constants used when saving/restoring state
private static final String BILL_TOTAL = "BILL_TOTAL";
private static final String CUSTOM_PERCENT = "CUSTOM_PERCENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tip_calculator);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tip_calculator, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private double currentBillTotal; // Bill as entered by the user
private int currentCustomPercent; // Custom tip % as set by user
private EditText billEditText; // Bill input widget
private EditText tip10EditText; // 10% tip output
private EditText tip15EditText; // 15% tip output
private EditText tip20EditText; // 20% tip output
private EditText tipCustomEditText; // ##% tip output
private EditText total10EditText; // 10% total output
private EditText total15EditText; // 15% total output
private EditText total20EditText; // 20% total output
private EditText totalCustomEditText; // ##% total output
private TextView customTipTextView; // Custom tip % output
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
currentBillTotal = 0;
currentCustomPercent = 18;
}
else
{
currentBillTotal = savedInstanceState.getDouble(BILL_TOTAL);
currentCustomPercent = savedInstanceState.getInt(CUSTOM_PERCENT);
}
View rootView = inflater.inflate(R.layout.fragment_tip_calculator, container, false);
tip10EditText = (EditText) rootView.findViewById(R.id.tip10EditText);
tip15EditText = (EditText) rootView.findViewById(R.id.tip15EditText);
tip20EditText = (EditText) rootView.findViewById(R.id.tip20EditText);
tipCustomEditText = (EditText) rootView.findViewById(R.id.tipCustomEditText);
total10EditText = (EditText) rootView.findViewById(R.id.total10EditText);
total15EditText = (EditText) rootView.findViewById(R.id.total15EditText);
total20EditText = (EditText) rootView.findViewById(R.id.total20EditText);
totalCustomEditText = (EditText) rootView.findViewById(R.id.totalCustomEditText);
customTipTextView = (TextView) rootView.findViewById(R.id.customTipTextView);
billEditText = (EditText) rootView.findViewById(R.id.billEditText);
//System.out.print(billEditText);
billEditText.addTextChangedListener(billEditTextWatcher);
SeekBar customSeekBar = (SeekBar) rootView.findViewById(R.id.customSeekBar);
customSeekBar.setOnSeekBarChangeListener(customSeekBarListener);
return rootView;
}
/**
* Calls {#link #updateStandard()} and then {#link #updateCustom()}.
*
* #see #updateStandard()
* #see #updateCustom()
*/
public void updateAll()
{
updateStandard();
updateCustom();
}
public void updateStandard()
{
calculateTipAndTotal(tip10EditText, total10EditText, .1);
calculateTipAndTotal(tip15EditText, total15EditText, .15);
calculateTipAndTotal(tip20EditText, total20EditText, .2);
}
public void updateCustom()
{
customTipTextView.setText(currentCustomPercent + "%");
calculateTipAndTotal(tipCustomEditText, totalCustomEditText, currentCustomPercent);
}
public void calculateTipAndTotal(EditText tipEditText, EditText totalEditText, double tip)
{
tipEditText .setText(String.format("%.02f", currentBillTotal * tip));
totalEditText.setText(String.format("%.02f", currentBillTotal * (tip + 1)));
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putDouble(BILL_TOTAL, currentBillTotal);
outState.putInt(CUSTOM_PERCENT, currentCustomPercent);
}
private SeekBar.OnSeekBarChangeListener customSeekBarListener =
new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
currentCustomPercent = seekBar.getProgress();
updateCustom();
}
#Override public void onStartTrackingTouch(SeekBar seekBar){}
#Override public void onStopTrackingTouch(SeekBar seekBar){}
}
;
private TextWatcher billEditTextWatcher =
new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try
{
currentBillTotal = extractDouble(s);
}
catch (NumberFormatException ex) // if we still didn't get a number
{
currentBillTotal = 0;
}
updateAll();
}
#Override public void beforeTextChanged(CharSequence s, int start, int count, int after){}
#Override public void afterTextChanged(Editable editable){}
}
;
/**
* Attempts to extract the first double found. This ideally works with percents, currency
* notation, and other formats where the double is surrounded by delimiters and text, but is
* not interrupted by it.<br/>
*<br/>
* A double may look like any one of these, where {#code #} represents any number of digits 0
* through 9:
*
* <ul>
* <li>{#code #}</li>
* <li>{#code .#}</li>
* <li>{#code #.#}</li>
* </ul>
*
* #param possibleDouble a character sequence that might contain a double
*
* #return the extracted double
*
* #throws java.lang.NumberFormatException if a double could not be found
*/
public static double extractDouble(CharSequence possibleDouble)
{
/**
* Matches at least one digit, optionally preceded by a radix point, optionally preceded by
* any number of digits
*/
Matcher matcher = Pattern.compile("([0-9]*\\.)?[0-9]+").matcher(possibleDouble);
matcher.find();
return Double.parseDouble(matcher.group());
}
}
}
activity_tip_calculator.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TipCalculator"
tools:ignore="MergeRootFrame" >
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="org.bh.tipcalculator2.TipCalculator$PlaceholderFragment"
android:id="#+id/fragmentTipCalculator"
android:layout_gravity="center"
tools:layout="#layout/fragment_tip_calculator" />
</FrameLayout>
fragment_tip_calculator.xml
<TableLayout 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=".TipCalculator$PlaceholderFragment"
android:id="#+id/tableLayout"
android:stretchColumns="#string/tableLayoutStretchColumns">
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow0"
android:gravity="center_vertical|right">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/billTotalLabel"
android:id="#+id/billTextView"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/billEditText"
android:inputType="numberDecimal"
android:layout_span="3"
android:text="#string/zeroCurrency"
android:selectAllOnFocus="false"
android:focusable="true"
android:focusableInTouchMode="true"
android:editable="true"
android:textIsSelectable="false"
android:textColor="#android:color/primary_text_dark"
android:hint="#string/billTotalHint"
android:enabled="true" />
<!--NumberPicker
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/billNumberPicker"
android:layout_span="3" /-->
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow2" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tipTextLabel"
android:id="#+id/tipLabelTextView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/tip10EditText"
android:layout_weight="0"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark"
android:text="#string/zeroCurrency" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/tip15EditText"
android:layout_weight="0"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark"
android:text="#string/zeroCurrency" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/tip20EditText"
android:layout_weight="0"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark"
android:text="#string/zeroCurrency" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tenPercent"
android:id="#+id/tenTextView"
android:layout_column="1"
android:gravity="center_horizontal|bottom"
android:textColor="#android:color/secondary_text_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/fifteenPercent"
android:id="#+id/fifteenTextView"
android:gravity="center_horizontal|bottom"
android:textColor="#android:color/secondary_text_dark" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/twentyPercent"
android:id="#+id/twentyTextView2"
android:gravity="center_horizontal|bottom"
android:textColor="#android:color/secondary_text_dark" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow3" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/totalTextLabel"
android:id="#+id/textView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/total10EditText"
android:layout_weight="0"
android:text="#string/zeroCurrency"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/total15EditText"
android:layout_weight="0"
android:text="#string/zeroCurrency"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/total20EditText"
android:layout_weight="0"
android:text="#string/zeroCurrency"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/spacerTableRow"
android:layout_weight="1">
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow4"
android:layout_gravity="bottom">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/customTextLabel"
android:id="#+id/customTextView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/customSeekBar"
android:indeterminate="false"
android:indeterminateOnly="false"
android:layout_span="2"
android:max="200"
android:progress="18" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="#string/customTipReadoutPlaceholder"
android:id="#+id/customTipTextView"
android:gravity="center_vertical|left" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="#+id/tableRow5"
android:layout_gravity="bottom">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/tipTextLabel"
android:id="#+id/tipCustomTextView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/tipCustomEditText"
android:layout_weight="0"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark"
android:text="#string/zeroCurrency" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/totalTextLabel"
android:id="#+id/totalCustomTextView"
android:gravity="center_vertical|right"
android:textColor="#android:color/secondary_text_dark" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/totalCustomEditText"
android:layout_weight="0"
android:text="#string/zeroCurrency"
android:focusable="#bool/outputEditable"
android:enabled="#bool/outputEditable"
android:editable="#bool/outputEditable"
android:longClickable="#bool/outputEditable"
android:focusableInTouchMode="#bool/outputEditable"
android:clickable="#bool/outputEditable"
android:textColor="#android:color/primary_text_dark" />
</TableRow>
</TableLayout>
Problem is here:
public static class PlaceholderFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
currentBillTotal = 0;
currentCustomPercent = 18;
}
When you create the view for the PlaceholderFragment, you're actually creating another PlaceholderFragment and adding it too. This will keep running and consuming memory until it's completely exhausted (and crashes).
In short, you should remove that part. The fragment has already been added.