Cannot populate listView through arrayAdapter - android

I'm new to both android and java, and following some tutorials outside of college assignments. Currently, I'm following a phonebook tutorial, but cannot get the contacts to populate the listView.
Would hugely appreciate any help - be it with this problem or learning Android dev in general.
Thanks!
public class Creator extends AppCompatActivity{
protected EditText _name;
protected EditText _phoneNumber;
protected EditText _email;
protected EditText _address;
List<Contact> Contacts = new ArrayList<Contact>();
ListView contactListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creator);
_name = (EditText) findViewById(R.id.inputName);
_phoneNumber = (EditText) findViewById(R.id.inputPhone);
_email = (EditText) findViewById(R.id.inputEmail);
_address = (EditText) findViewById(R.id.inputAddress);
TabHost tabHost = (TabHost)findViewById(R.id.tabHost);
contactListView = (ListView) findViewById(R.id.listView);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("Creator");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("contacts");
tabSpec.setContent(R.id.tabContacts);
tabSpec.setIndicator("Contacts");
tabHost.addTab(tabSpec);
final Button btnSave = (Button)findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addContact(_name.getText().toString(), _phoneNumber.getText().toString(), _email.getText().toString(), _address.getText().toString());
populateList();
Toast.makeText(getApplicationContext(), _name.getText().toString() +" has been added to your contacts",Toast.LENGTH_SHORT).show();
}
});
_name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
btnSave.setEnabled(!_name.getText().toString().trim().isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void populateList(){
ArrayAdapter<Contact> adapter = new ContactListAdapter();
contactListView.setAdapter(adapter);
}
private void addContact(String name, String number, String email, String address){
Contacts.add(new Contact(name, number, email, address));
}
private class ContactListAdapter extends ArrayAdapter<Contact>{
public ContactListAdapter(){
super(Creator.this, R.layout.contacts, Contacts);
}
#Override
public View getView(int position, View view, ViewGroup parent){
if (view == null)
view = getLayoutInflater().inflate(R.layout.contacts, parent, false);
Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.textName);
name.setText(currentContact.getName());
TextView number = (TextView) view.findViewById(R.id.textNumber);
number.setText(currentContact.getNumber());
TextView email = (TextView) view.findViewById(R.id.textEmail);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.textAddress);
address.setText(currentContact.getAddress());
return view;
}
}
}
<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"
tools:context="com.example.davel.phonebook.Creator"
android:orientation="vertical">
<TabHost
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabHost">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/tabContacts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="ContactList"
android:id="#+id/textContactsHead"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:id="#+id/tabCreator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Create Contact"
android:id="#+id/textView2"
android:layout_below="#+id/inputPhone"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inputName"
android:width="300dp"
android:hint="Name"
android:layout_below="#+id/btnSave"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inputPhone"
android:width="300dp"
android:hint="Phone number"
android:phoneNumber="true"
android:inputType="phone"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inputEmail"
android:width="300dp"
android:inputType="textEmailAddress"
android:hint="Email" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inputAddress"
android:width="300dp"
android:inputType="textMultiLine"
android:hint="Address"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="#+id/btnSave"
android:width="150dp"
android:layout_gravity="center_horizontal"
android:clickable="false"
android:contextClickable="false"
android:enabled="false"
android:onClick="btnClick"
/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>

Related

Fragment editText data getting cleared when i am moving to another activity and coming back

I have an FragmentActivity which contain WebView, Edittext1, Edittext2, Checkboxes and button. When I click the button in fragment it will move to Results_activity. And if I click button from Results_activity it move back to FragmentActivity.
But my edittext values getting cleared while moving back.
FragmentActivity 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"
android:background="#android:color/background_light"
android:orientation="vertical">
<LinearLayout
android:id="#+id/questionContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<WebView
android:id="#+id/questionWV"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/ansA_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp">
<EditText
android:id="#+id/ansA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:freezesText="true"
android:hint="Enter answer here..."
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:textAppearance="#android:style/TextAppearance.Medium" />
</LinearLayout>
<LinearLayout
android:id="#+id/ansB_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp">
<EditText
android:id="#+id/ansB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:freezesText="true"
android:hint="Enter answer here..."
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:textAppearance="#android:style/TextAppearance.Medium" />
</LinearLayout>
<LinearLayout
android:id="#+id/answers_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:paddingRight="5dp"
android:paddingBottom="5dp">
<RelativeLayout
android:id="#+id/answer_a_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="top"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:hint="0"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta A"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/answer_b_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="false"
android:layout_marginStart="15dp"
android:hint="1"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta B"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/answer_c_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:hint="2"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta C"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/answer_d_container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<CheckBox
android:id="#+id/answerD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:hint="3"
android:maxLines="100"
android:minWidth="50dp"
android:minHeight="50dp"
android:scrollbars="vertical"
android:text="Varianta D"
android:textAppearance="#android:style/TextAppearance.Medium" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom|center"
android:orientation="horizontal"
android:paddingBottom="30dp">
<Button
android:id="#+id/btnFinishTest"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/testbutton"
android:onClick="FinishTest"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Finish Test" />
<Button
android:id="#+id/btnAnswer"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/testbutton"
android:onClick="SubmitAnswer"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Submit Answer" />
</LinearLayout>
</LinearLayout>
Fragment Code
my edittexts are et1 and et2
public class QuestionFragment2018ii extends Fragment {
LinearLayout answersContainer;
int currentPageNr;
private String input1;
#Override
public View onCreateView(LayoutInflater lInflater, ViewGroup container,Bundle saveInstanceState){
currentPageNr = getArguments().getInt("position");
//initialize some variables
final Question2018ii currentQuestion2018ii = MyServerData2018ii.getInstance().getQuestion(currentPageNr);
View rootView = lInflater.inflate(R.layout.quiz_activity_fragment,container,false);
//initialize show answer option
final String ans = currentQuestion2018ii.getExplanationText();
final EditText et1 = rootView.findViewById(R.id.ansA);
final EditText et2 = rootView.findViewById(R.id.ansB);
if(MyServerData2018ii.getInstance().getTestState().equals("finished") ){
et1.setText("Your Response: " + et.getText());
et2.setText("Correct Answer: " + ans);
}
//initialize Explanation option
//initialize answers
answersContainer = (LinearLayout)rootView.findViewById(R.id.answers_container);
String[] answers = currentQuestion2018ii.getAllAnswersText();
for (int i = 0; i < answersContainer.getChildCount(); i++) {
RelativeLayout checkboxContainer = (RelativeLayout)answersContainer.getChildAt(i);
CheckBox cb = (CheckBox)checkboxContainer.getChildAt(0);
cb.setMovementMethod(new ScrollingMovementMethod());
cb.setText(answers[i]);
cb.setChecked(currentQuestion2018ii.isChecked(i));
if(MyServerData2018ii.getInstance().getTestState().equals("finished") ){
cb.setEnabled(false);
questionWebView.loadUrl("file:///android_asset/" + currentQuestion2018ii.getSolutionText());
//check if answer is right or wrong
if(currentQuestion2018ii.isCorrectAnswer(i)){
cb.setTextColor(Color.parseColor("#4DAD47"));
cb.setTypeface(null, Typeface.BOLD);
} else {
cb.setTextColor(Color.parseColor("#CE0B0B"));
}
}else{
cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = ((CheckBox) v);
int number = Integer.parseInt(cb.getHint().toString());
currentQuestion2018ii.setChecked(number, cb.isChecked());
}
});
}
}
return rootView;
}
}
ResultsActivity xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:paddingTop="30dp"
android:text="#string/results"
android:textColor="#4DAD47"
android:textSize="20sp"
android:textStyle="bold|italic" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingTop="30dp" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:paddingBottom="20dp"
android:text="#string/correct_answers" />
</LinearLayout>
<TextView
android:id="#+id/myTotalAnswers"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical|center_horizontal"
android:paddingRight="5dp"
android:text="50/100" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainContainer"></LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<Button
android:id="#+id/check_results"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/testbutton"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/check_results" />
<Button
android:id="#+id/btnMainMenu"
style="#android:style/Widget.Button.Inset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#drawable/testbutton"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="#string/main_menu" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
Quiz activity
public class QuizActivity2018ii extends AppCompatActivity {
Spinner spinCategory;
EditText questionNr;
ArrayList<String> allCategories;
int totalQuestions;
AlertDialog dialog;
ViewPager pager;
QuestionPagerAdapter2018ii pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_activity_view_pager);
allCategories = new ArrayList<>(MyServerData2018ii.getInstance().getCategoryList());
totalQuestions = MyServerData2018ii.getInstance().getTotalQuestions();
//initialize category spinner
ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item,allCategories);
spinCategory = (Spinner) findViewById(R.id.category);
spinCategory.setAdapter(categoryAdapter);
spinCategory.setSelection(0);
//set Category spinner callback
spinCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String currentQuestionRealCategory = MyServerData2018ii.getInstance().getQuestionCategory(pager.getCurrentItem());
String selectedCategory = spinCategory.getItemAtPosition(position).toString();
if (!selectedCategory.equals(currentQuestionRealCategory)) {
int firstQuestionNumberFromCategory = MyServerData2018ii.getInstance().getFirstQuestionNumberFromCategory(selectedCategory);
ViewPager pager = (ViewPager) findViewById(R.id.qPager);
pager.setCurrentItem(firstQuestionNumberFromCategory, false);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//initialize number
questionNr = (EditText) findViewById(R.id.dialog_question_number);
questionNr.clearFocus();
//set number callbacks
questionNr.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_ENTER)) {
v.clearFocus();
CharSequence s = questionNr.getText();
if (!s.toString().isEmpty()) {
Integer questionNumber = Integer.parseInt(s.toString());
//avoids out of range indexes
if (questionNumber > totalQuestions + 1) {
questionNumber = totalQuestions;
}
if (questionNumber < 0) {
questionNumber = 1;
}
//create looping effect
if (questionNumber == totalQuestions + 1) {
questionNumber = 1;
((EditText)v).setText("1");
}
if (questionNumber == 0) {
questionNumber = totalQuestions;
((EditText)v).setText(String.valueOf(totalQuestions));
}
ViewPager pager = (ViewPager) findViewById(R.id.qPager);
pager.setCurrentItem(questionNumber, false);
questionNr.clearFocus();
} else {
questionNr.setText("1");
}
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return false;
}
});
//initialize pager
pager = (ViewPager)findViewById(R.id.qPager);
pagerAdapter = new QuestionPagerAdapter2018ii(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
pager.setCurrentItem(1, false);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
Integer currentQuestion = pager.getCurrentItem();
//change spinner
String currentCategory = MyServerData2018ii.getInstance().getQuestionCategory(currentQuestion);
int categoryPosition = MyServerData2018ii.getInstance().getCategoryList().indexOf(currentCategory);
spinCategory.setSelection(categoryPosition);
//change numberPicker
if(currentQuestion <= 0){currentQuestion = totalQuestions;}
if(currentQuestion > totalQuestions){currentQuestion = 1;}
questionNr.setText(currentQuestion.toString());
questionNr.clearFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(questionNr.getWindowToken(), 0);
}
#Override
public void onPageScrollStateChanged(int state) {
int totalQuestions = MyServerData2018ii.getInstance().getTotalQuestions();
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (pager.getCurrentItem() == totalQuestions + 1) {
pager.setCurrentItem(1, false);
}
if (pager.getCurrentItem() == 0) {
pager.setCurrentItem(totalQuestions, false); // false will prevent sliding animation of view pager
}
}
}
});
}
public void FinishTest(View v){
//check if there are unanswered questions
if(MyServerData2018ii.getInstance().getTestState().equals("inProgress")){
ArrayList<String> UnansweredQuestions = new ArrayList<>();
LinkedHashMap<String,Object> allQuestions = MyServerData2018ii.getInstance().getAllQuestions();
for(Map.Entry category: allQuestions.entrySet()){
Question2018ii[] question2018iis = (Question2018ii[])category.getValue();
for(int i = 0; i < question2018iis.length; i++){
Boolean[] userAnswers = question2018iis[i].getUserAnswers();
if(!Arrays.asList(userAnswers).contains(true)){
String checkedCategory = (String)category.getKey();
Integer questionNumberInList = MyServerData2018ii.getInstance().getQuestionListNumber(checkedCategory,i);
UnansweredQuestions.add(String.valueOf(questionNumberInList));
}
}
}
if(UnansweredQuestions.size() > 0){
dialog = new AlertDialog.Builder(this)
.create();
LayoutInflater infl = LayoutInflater.from(this);
dialog.setView(infl.inflate(R.layout.dialog_message,null));
dialog.show();
TextView message = (TextView)dialog.findViewById(R.id.message);
String unfinished = getResources().getString(R.string.unfinished_text);
String questions = TextUtils.join(",",UnansweredQuestions);
message.setText(unfinished + "\n" + questions + ".");
dialog.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
showResults();
}
});
}else{showResults();}
}else{
showResults();
}
}
public void showResults(){
int animationDuration;
if(MyServerData2018ii.getInstance().getTestState().equals("finished")){
animationDuration = 10;
}else{
animationDuration = 2000;
}
View mainView = LayoutInflater.from(this).inflate(R.layout.quiz_activity_show_results,null);
LinearLayout mainContainer = (LinearLayout)mainView.findViewById(R.id.mainContainer);
mainView.findViewById(R.id.btnMainMenu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//finish the test and go to main menu
Intent Main = new Intent(getApplicationContext(),MainActivity.class);
finish();
startActivity(Main);
MyServerData2018ii.getInstance().setTestState("notStarted");
MyServerData2018ii.getInstance().clearAnswers();
Toast.makeText(getBaseContext(),R.string.text_ended,Toast.LENGTH_LONG).show();
}
});
mainView.findViewById(R.id.check_results).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
Question2018ii[] currentCategory;
int totalCategoryQuestions;
int correctCategoryQuestions;
int totalCorrectQuestions = 0;
//checking and adding each category
for(String category: allCategories){
View categoryContainer = LayoutInflater.from(this).inflate(R.layout.quiz_activity_category_results,null);
TextView categoryName = (TextView)categoryContainer.findViewById(R.id.categoryName);
//set name
categoryName.setText(category);
currentCategory = MyServerData2018ii.getInstance().getCategory(category);
totalCategoryQuestions = currentCategory.length;
//check answers
correctCategoryQuestions = 0;
for(int i=0; i < currentCategory.length;i++){
Boolean isCorrect = Arrays.equals(currentCategory[i].getAllCorrectAnswers(),currentCategory[i].getUserAnswers());
if(isCorrect){ correctCategoryQuestions++;}
}
totalCorrectQuestions += correctCategoryQuestions;
//set results
String result = String.valueOf(correctCategoryQuestions) + "/" + String.valueOf(totalCategoryQuestions);
final ProgressBar progress = (ProgressBar)categoryContainer.findViewById(R.id.progressBar);
progress.setMax(totalCategoryQuestions*100);
final TextView myResult = (TextView)categoryContainer.findViewById(R.id.categoryResult);
final String myResultText = "/" + String.valueOf(totalCategoryQuestions);
ValueAnimator val = new ValueAnimator();
val.setObjectValues(0, correctCategoryQuestions*100);
val.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
myResult.setText(String.valueOf((Integer)animation.getAnimatedValue()/100) + myResultText);
progress.setProgress( ((Integer) animation.getAnimatedValue()));
}
});
val.setDuration(animationDuration);
val.start();
mainContainer.addView(categoryContainer);
}
//animate results
final TextView tvTotalResult =(TextView)mainView.findViewById(R.id.myTotalAnswers);
final String totalResultS = "/" + String.valueOf(totalQuestions);
ValueAnimator totalResultsAnimator = new ValueAnimator();
totalResultsAnimator.setObjectValues(0, totalCorrectQuestions);
totalResultsAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
tvTotalResult.setText(String.valueOf(animation.getAnimatedValue()) + totalResultS);
}
});
totalResultsAnimator.setDuration(animationDuration);
totalResultsAnimator.start();
MyServerData2018ii.getInstance().setTestState("finished");
setContentView(mainView);
}
}
this is my question yearwise activity(from this I launched the fragment activity)
public class QuestionYearwise extends AppCompatActivity{
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.question_yearwise);
Button btn2018ii = (Button)findViewById(R.id.btn2018ii);
btn2018ii.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Quiz2018ii = new Intent(getApplicationContext(),QuizActivity2018ii.class);
MyServerData2018ii.getInstance().setTestState("inProgress");
startActivity(Quiz2018ii);
}
});
}
}
Replace the method like this,
mainView.findViewById(R.id.check_results).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});

Display corresponding details of user when selected from list

I have developed a screen where a no. of people from the database are displayed in a list view. I want to display the profile page of the selected person. So my question is how to bind each detail of the selected person like name, contact, etc. to the profile page which I have created? Will I have to call the getById API in the onItemClickListener?
Here's the edited code:-
public class Test extends AppCompatActivity {
List<Genie> genieList;
GenieAdapter genieAdapter;
TextView responseView;
ProgressBar progressBar;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
responseView = (TextView) findViewById(R.id.responseView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
button = (Button) findViewById(R.id.test);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Test.this, "Blahblah", Toast.LENGTH_LONG).show();
new RetrieveFeedTask().execute();
}
});
}
class RetrieveFeedTask extends AsyncTask<Void, Void, List<Genie>> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
}
protected List<Genie> doInBackground(Void... urls) {
GenieService genieService = new GenieService();
return genieService.getAll();
}
protected void onPostExecute(List<Genie> genies) {
if (genies == null) {
new ArrayList<Genie>(); // "THERE WAS AN ERROR"
} else {
progressBar.setVisibility(View.GONE);
Log.i("INFO", genies.get(0).name);
List<String> rows = genies.stream().map(genie -> getRow(genie)).collect(Collectors.toList());
genieAdapter=new GenieAdapter(getApplicationContext(),R.layout.genie_list, genies);
ListView list=(ListView)findViewById(R.id.listViewMain);
list.setAdapter(genieAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(Test.this, "" + position, Toast.LENGTH_SHORT).show();
// if (position == 1) {
// startActivity(new Intent(Test.this, viewGenie1.class));
// }
}
});
list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Test.this, viewGenie1.class);
intent.putExtra("name", "%s");
intent.putExtra("add", "%s");
intent.putExtra("phn", "%s");
intent.putExtra("sal", "%s");
intent.putExtra("lea", "%s");
startActivity(intent);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
private String getRow(Genie g) {
return String.format("%s, %s, %s, %s, %s", g.name, g.salary, g.contact, g.paid_leaves, g.address);
}
}
}
Here's the viewGenie1.class:-
public class viewGenie1 extends AppCompatActivity implements View.OnClickListener {
TextView name;
EditText address, contact, salary, leaves;
Button attendance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_genie1);
name = (TextView) findViewById(R.id.txName);
address = (EditText) findViewById(R.id.txAddress);
contact = (EditText) findViewById(R.id.txContact);
salary = (EditText) findViewById(R.id.txSalary);
leaves = (EditText) findViewById(R.id.txLeaves);
Button update=(Button)findViewById(R.id.btUpdate);
update.setOnClickListener(this);
Button delete=(Button)findViewById(R.id.delete);
delete.setOnClickListener(this);
Button attendance = (Button) findViewById(R.id.attendance);
attendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAtt();
}
});
String value = "";
if (getIntent().hasExtra("name")) {
String name = getIntent().getExtras().getString("name");
String add = getIntent().getExtras().getString("add");
String phn = getIntent().getExtras().getString("phn");
String sal = getIntent().getExtras().getString("sal");
String lea = getIntent().getExtras().getString("lea");
}
name.setText(value);
address.setText(value);
contact.setText(value);
salary.setText(value);
leaves.setText(value);
}
#Override
public void onClick(View view) {
final AlertDialog.Builder builder=new AlertDialog.Builder(viewGenie1.this);
builder.setMessage("Are you sure you want to delete records?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
new deleteTask().execute();
Toast.makeText(viewGenie1.this, "Genie deleted..!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(viewGenie1.this, navDrawer.class));
// GenieService genieService=new GenieService();
// genieService.delete(2);
// Log.d("Information", String.valueOf(genieService.delete(2)));
// Log.i("INFO", genies.get(0).name);
// startActivity(new Intent(viewGenie1.this,Test.class));
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert=builder.create();
alert.show();
}
private class deleteTask extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
GenieService genieService = new GenieService();
return genieService.delete(6);
}
}
public void showAtt() {
Intent intent = new Intent(this, viewAbsentee.class);
startActivity(intent);
}
}
Here's the xml file of the profile page I have created with hard coded values but want to display the actual values from the local mysql database using an API call:-
<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"
android:background="#drawable/bcak"
tools:context="com.codionics.geniem.AddGenie"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="313dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#drawable/gradientbackground"
android:orientation="vertical">
<ImageView
android:layout_width="117dp"
android:layout_height="117dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:src="#drawable/genie" />
<TextView
android:id="#+id/txName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Abc"
android:textColor="#ffffff"
android:textSize="21sp"
android:textStyle="bold" />
</LinearLayout>
<android.support.v7.widget.CardView
android:layout_width="300dp"
android:layout_height="115dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="175dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Contact"
android:textColor="#f000"
android:textStyle="bold"
android:textSize="20sp" />
<EditText
android:id="#+id/txContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="123456789"
android:textColor="#3F51B5"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textColor="#f000"
android:textSize="20sp"
android:textStyle="bold" />
<EditText
android:id="#+id/txAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:text="Pune"
android:textColor="#3F51B5"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<LinearLayout
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="42dp"
android:paddingLeft="25dp">
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="center"
android:src="#drawable/ic_attach_money_black_24dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="20dp"
android:text="Paid leaves : "
android:textColor="#303F9F"
android:textSize="27dp"
android:textStyle="bold" />
<EditText
android:id="#+id/txLeaves"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:layout_weight="1"
android:text=" 5" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="42dp"
android:paddingLeft="25dp">
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_gravity="center"
android:src="#drawable/ic_money" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="20dp"
android:text="Salary : "
android:textColor="#303F9F"
android:textSize="27dp"
android:textStyle="bold" />
<EditText
android:id="#+id/txSalary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:text=" 5000"
android:textColor="#123" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/btUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginTop="30dp"
android:background="#drawable/buttonstylegradient"
android:text="Update Genie"
android:textColor="#fff" />
<Button
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginRight="80dp"
android:layout_marginTop="-50dp"
android:background="#drawable/buttonstylegradient"
android:text="Delete Genie"
android:textColor="#fff" />
<Button
android:id="#+id/attendance"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/buttonstylegradient"
android:textColor="#fff"
android:text="Attendance" />
</LinearLayout>
I want to display the details in the a profile page like this:-
profile page
Please pass the value in Intent using putExtra()
Intent intent = new Intent(Test.this, viewGenie1.class);
intent.putExtra("key","Value"); //Key must be unique and value should be the value which you want to pass to viewGenie1 class.
startActivity(intent);
In viewGenie1 class you can get the value like this
String value="";
if(getIntent().hasExtra("key")) {
value = getIntent().getExtras().getString("key");
}
Please replace
String value = "";
if (getIntent().hasExtra("name")) {
String name = getIntent().getExtras().getString("name");
String add = getIntent().getExtras().getString("add");
String phn = getIntent().getExtras().getString("phn");
String sal = getIntent().getExtras().getString("sal");
String lea = getIntent().getExtras().getString("lea");
}
name.setText(value);
address.setText(value);
contact.setText(value);
salary.setText(value);
leaves.setText(value);
To
String mName = "",mAdd="",mPhn="",mSal="",mLea="";
if (getIntent().hasExtra("name")) {
mName = getIntent().getExtras().getString("name");
mAdd = getIntent().getExtras().getString("add");
mPhn = getIntent().getExtras().getString("phn");
mSal = getIntent().getExtras().getString("sal");
mLea = getIntent().getExtras().getString("lea");
}
name.setText(mName);
address.setText(mAdd);
contact.setText(mPhn);
salary.setText(mSal);
leaves.setText(mLea);

android setting onclicklistener on button in listview

Updated!
I've created a custom listview and so far i've tried implementing listeners on a button but it doesnt work
here's my main activity
public class homepage extends Activity {
ListView list;
String[] Name = {
"Lovelle Ong",
"Ryan Lopez",
"Melissa Gan"
} ;
String[] Location = {
"Botanical Gardens",
"Cape Town",
"Gardens By the Bay"
} ;
Integer[] imageId = {
R.drawable.lovelle,
R.drawable.ryanlopez,
R.drawable.melissa
};
Integer[] mainId = {
R.drawable.likedpage1,
R.drawable.commentpage,
R.drawable.melissap
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
CustomList adapter = new
CustomList(homepage.this, Name, Location, imageId, mainId);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setClickable(true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + Name [position], Toast.LENGTH_LONG)
.show(); //this doesn't work too
}
});
ImageButton back = (ImageButton) findViewById(R.id.imageButton1);
back.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MainPage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
}
}
my adapter class
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] Name, Location;
private final Integer[] imageId, mainId;
public CustomList(Activity context,
String[] Name, String[] Location, Integer[] imageId, Integer[] mainId) {
super(context, R.layout.list_single, Name);
this.context = context;
this.Name = Name;
this.imageId = imageId;
this.Location = Location;
this.mainId = mainId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView name = (TextView) rowView.findViewById(R.id.textView1);
TextView location = (TextView) rowView.findViewById(R.id.textView2);
ImageView profileView = (ImageView) rowView.findViewById(R.id.imageView1);
Button mainImage = (Button) rowView.findViewById(R.id.profilepagelist1);
Button comment = (Button) rowView.findViewById(R.id.buttonComment);
final Button emptyheart = (Button) rowView.findViewById(R.id.imageView3);
final Button filledheart = (Button) rowView.findViewById(R.id.ImageViewRight);
emptyheart.setOnClickListener(new View.OnClickListener() //thisworks
{
#Override
public void onClick(View v) {
emptyheart.setVisibility(View.INVISIBLE);
filledheart.setVisibility(View.VISIBLE);
}
});
filledheart.setOnClickListener(new View.OnClickListener() //thisworks
{
#Override
public void onClick(View v) {
emptyheart.setVisibility(View.VISIBLE);
filledheart.setVisibility(View.INVISIBLE);
}
});
comment.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Log.d("fail", null, null);
// this.startActivity(new Intent(getBaseContext().this, commentpage.class)); <---- errors here
}
});
name.setText(Name[position]);
location.setText(Location[position]);
profileView.setImageResource(imageId[position]);
mainImage.setBackgroundResource(mainId[position]);
return rowView;
}
}
my list_single.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="com.example.muc2.MainActivity"
tools:ignore="MergeRootFrame" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/mega1">
<LinearLayout
android:layout_width="match_parent"
android:paddingLeft="2dp"
android:paddingTop="2dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="5dp"
>
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/nameholders"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingLeft="5dp"
android:text="Lovelle Ong"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/buttonComment"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toLeftOf="#+id/imageView3"
android:background="#drawable/comment" />
<ImageView
android:id="#+id/imageView3"
android:layout_alignParentRight="true"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/like" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_alignParentLeft="true"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="23dp"
android:layout_height="23dp"
android:src="#drawable/geoicon" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingLeft="2dp"
android:paddingTop="2dp" >
<Button
android:id="#+id/profilepagelist1"
android:layout_width="fill_parent"
android:layout_height="310dp"
android:layout_centerInParent="true"
android:paddingBottom="5dp"
android:paddingLeft="2dp"
android:paddingRight="2dp" />
</RelativeLayout>
</LinearLayout>
and lastly the xml file that contains the list view
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
tools:context="com.example.muc2.MainActivity$PlaceholderFragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:orientation="vertical"
>
<RelativeLayout
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#drawable/exit"
android:maxHeight="35dp"
android:maxWidth="35dp"
android:paddingBottom="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="2dp"
android:layout_alignParentRight="false"
/>
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#drawable/momentlogowhite"
android:maxHeight="35dp"
android:maxWidth="35dp"
android:paddingBottom="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="2dp"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Is there a way for me to implement a listener on a button and upon clicking it, it leads me to the next activity?
thanks and sorry for the long post!
i was able to see upon clicking it but when i put an intent for it to
switch from one activity to another it came with errors. i only used
the log.d to find out whether the button work
startActivity is a method of Activity class. So you need Activity Context. You already have
this.context = context;
So Use
context.startActivity(new Intent(context, commentpage.class));

Layout issue, big vertical space between the viewtext elemens and divider in list item

below is a list_item layout. I don't understand why there is a big vertical space between the viewtext elemens and divider element inside a list item row ? What is wrong with this layout?
Screenshot here
My layout xml for list item:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/companyName"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:singleLine="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/table_text_selector"/>
<TextView
android:id="#+id/exchange"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/table_text_light_selector"
android:layout_below="#id/companyName"/>
<TextView
android:id="#+id/symbol"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/table_text_light_selector"
android:layout_below="#id/companyName"
android:layout_toLeftOf="#id/exchange"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:singleLine="true"
android:ellipsize="end"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/table_text_selector"
android:layout_alignParentRight="true"/>
<TextView
android:id="#+id/change"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/table_stock_change_text"
android:layout_alignParentRight="true"
android:layout_below="#id/price"/>
<TextView
android:id="#+id/percentChange"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/table_stock_change_text"
android:layout_alignBaseline="#id/change"
android:layout_alignBottom="#id/change"
android:layout_toLeftOf="#id/change"
android:layout_marginRight="5dp"/>
</RelativeLayout>
This is the fragment:
public class StockListFragment extends ItemListFragment<CurrentStock> {
#Inject BootstrapServiceProvider serviceProvider;
#Inject LogoutService logoutService;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Injector.inject(this);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText(R.string.no_stocks);
}
#Override
protected void configureList(Activity activity, ListView listView) {
super.configureList(activity, listView);
listView.setFastScrollEnabled(true);
listView.setDividerHeight(0);
getListAdapter().addHeader(activity.getLayoutInflater()
.inflate(R.layout.stock_list_item_labels, null));
}
#Override
LogoutService getLogoutService() {
return logoutService;
}
#Override
public Loader<List<CurrentStock>> onCreateLoader(int id, Bundle args) {
final List<CurrentStock> initialItems = items;
return new ThrowableLoader<List<CurrentStock>>(getActivity(), items) {
#Override
public List<CurrentStock> loadData() throws Exception {
try {
List<CurrentStock> latest = null;
if(getActivity() != null)
latest = serviceProvider.getService(getActivity()).getStocks();
if (latest != null)
return latest;
else
return Collections.emptyList();
} catch (OperationCanceledException e) {
Activity activity = getActivity();
if (activity != null)
activity.finish();
return initialItems;
}
}
};
}
public void onListItemClick(ListView l, View v, int position, long id) {
CurrentStock currentStock = ((CurrentStock) l.getItemAtPosition(position));
startActivity(new Intent(getActivity(), StockActivity.class).putExtra(STOCK, currentStock));
}
#Override
public void onLoadFinished(Loader<List<CurrentStock>> loader, List<CurrentStock> items) {
super.onLoadFinished(loader, items);
}
#Override
protected int getErrorMessage(Exception exception) {
return R.string.error_loading_stocks;
}
#Override
protected SingleTypeAdapter<CurrentStock> createAdapter(List<CurrentStock> items) {
return new StockListAdapter(getActivity().getLayoutInflater(), items);
}
}
This is the adapter
public class StockListAdapter extends SingleTypeAdapter<CurrentStock> {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MMMM dd");
/**
* Create adapter
*
* #param inflater
* #param items
*/
public StockListAdapter(LayoutInflater inflater, List<CurrentStock> items) {
super(inflater, R.layout.stock_list_item);
setItems(items);
}
/**
* Create adapter
*
* #param inflater
*/
public StockListAdapter(LayoutInflater inflater) {
this(inflater, null);
}
#Override
public long getItemId(final int position) {
final String id = getItem(position).getSymbol();
return !TextUtils.isEmpty(id) ? id.hashCode() : super
.getItemId(position);
}
/**/
#Override
protected int[] getChildViewIds() {
return new int[] { R.id.companyName, R.id.exchange, R.id.symbol, R.id.price, R.id.change, R.id.percentChange };
}
#Override
protected void update(int position, CurrentStock currentStock) {
setText(0, currentStock.getCompanyName());
setText(1, currentStock.getExchange());
setText(2, currentStock.getSymbol());
setText(3, currentStock.getPrice().toString());
setText(4, currentStock.getChange().toString());
setText(5, currentStock.getPercentChange());
}
}
I don't have the listview it selvf. Btw. I need a divider except top and bottom divider ?
The problem lies in your code where you're using your divider code. By the way, why are you doing this? ... since ListView has its divider and dividerHeight?
Here's what I've came up with in a couple of minutes of coding using above layout (only removed the textColor attributes):
The code for above list:
public class MyListActivity extends FragmentActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.so_list_layout);
listView = (ListView) findViewById(R.id.localListView);
fillListView();
}
private void fillListView() {
final List<LDataRow> data = getRowData();
ArrayAdapter<LDataRow> adapter = new ArrayAdapter<MyListActivity.LDataRow>(this,
R.layout.so_list_row, data) {
private LDataRow getDataRow(int position) {
return data.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LDataRow row = getDataRow(position);
if (convertView == null) {
convertView = LayoutInflater.from(MyListActivity.this).inflate(
R.layout.so_list_row, parent, false);
}
TextView companyName = (TextView) convertView.findViewById(R.id.companyName);
companyName.setText(row.getCompanyName());
TextView exchange = (TextView) convertView.findViewById(R.id.exchange);
exchange.setText(row.getExchange());
TextView symbol = (TextView) convertView.findViewById(R.id.symbol);
symbol.setText(row.getSymbol());
TextView price = (TextView) convertView.findViewById(R.id.price);
price.setText(String.valueOf(row.getPrice()));
TextView change = (TextView) convertView.findViewById(R.id.change);
change.setText(String.valueOf(row.getChange()));
TextView percentChange = (TextView) convertView.findViewById(R.id.percentChange);
percentChange.setText(String.valueOf(row.getPercentChange()));
return convertView;
}
};
listView.setAdapter(adapter);
}
private List<LDataRow> getRowData() {
ArrayList<LDataRow> result = new ArrayList<MyListActivity.LDataRow>();
result.add(new LDataRow("Facebook", "Nasdaq", "E", 52.445, 0.0, 0));
result.add(new LDataRow("Advanced Micro", "NYSE", "D", 3.23, 0.0, 0));
result.add(new LDataRow("Genmas", "CPH", "G", -100, -3.0, -20.0));
return result;
}
private static class LDataRow {
private String companyName;
private String exchange;
private String symbol;
private double price;
private double change;
private double percentChange;
public LDataRow(String companyName, String exchange, String symbol, double price,
double change, double percentChange) {
this.companyName = companyName;
this.exchange = exchange;
this.symbol = symbol;
this.price = price;
this.change = change;
this.percentChange = percentChange;
}
public String getCompanyName() {
return companyName;
}
public String getExchange() {
return exchange;
}
public String getSymbol() {
return symbol;
}
public double getPrice() {
return price;
}
public double getChange() {
return change;
}
public double getPercentChange() {
return percentChange;
}
}
}
Use this in top RelativeLayout to have a bottom spacing:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="8dp" >
EDIT If you want to customize the divider, you can very well specify a custom drawable and a size. Here's what I've done with a simple layer-list, my_so_divider.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#ffffff" />
</shape>
</item>
<item>
<shape android:shape="line" >
<stroke
android:width="1dp"
android:color="#000000" />
</shape>
</item>
</layer-list>
Set it in the ListView:
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/localListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ffff"
android:divider="#drawable/my_so_divider"
android:dividerHeight="24dp"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false" >
</ListView>
Check the footerDividersEnabled, headerDividersEnabled, divider and dividerHeight attributes ... Feel free to play around with the drawable. The effect in below image:
// try this
<?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:padding="5dp">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/companyName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#color/table_text_light_selector"
android:text="companyName"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="#+id/symbol"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="symbol"/>
<TextView
android:id="#+id/exchange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="exchange"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:gravity="right"
android:orientation="vertical">
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="end"
android:textColor="#color/table_text_light_selector"
android:text="price"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<TextView
android:id="#+id/percentChange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="percentChange"
android:layout_marginTop="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginRight="5dp"/>
<TextView
android:id="#+id/change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="change"
android:layout_marginTop="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
Try the following code.. It will give you the similar result you are in need of:
<?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="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:gravity="center">
<TextView
android:id="#+id/companyName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:text="facebook"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:textColor="#color/table_text_selector"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="facebook"
android:layout_marginRight="5dp"
android:textColor="#color/table_text_selector"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/exchange"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="facebook"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:textColor="#color/table_text_light_selector"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/percentChange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="22%"
android:textColor="#color/table_stock_change_text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginRight="5dp"/>
<TextView
android:id="#+id/change"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0.0"
android:layout_marginRight="5dp"
android:textColor="#color/table_stock_change_text"
android:textAppearance="?android:attr/textAppearanceSmall"/>
</LinearLayout>
</LinearLayout>

Code optimisation. (Architecture)

I'm making a quiz app. User has to finish the phrase shown on display and write the name of the car in the edittext, after pushing on button, if the answer right, edittext become green, if doesn't, become red. If all answers right (green), intent move on next activity.
The question is: how to optimize my code, I don't like how it's look like? If I decide to add some more options it wouldn't be readable.
public class MainActivity extends AppCompatActivity {
EditText et_one_one, et_one_two, et_one_three;
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_one_one = (EditText) findViewById(R.id.et_one_one);
et_one_two = (EditText) findViewById(R.id.et_one_two);
et_one_three = (EditText) findViewById(R.id.et_one_three);
buttonCheck = (Button) findViewById(R.id.buttonCheck);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean allAnswersCorrect = true;
String t1 = et_one_one.getText().toString().toLowerCase();
String t2 = et_one_two.getText().toString().toLowerCase();
String t3 = et_one_three.getText().toString().toLowerCase();
if (t1.equals("maserati")){
et_one_one.setBackgroundColor(Color.GREEN);
}
else {
allAnswersCorrect = false;
et_one_one.setBackgroundColor(Color.RED);
}
if (t2.equals("mercedes")){
et_one_two.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_two.setBackgroundColor(Color.RED);
}
if (t3.equals("bmw")){
et_one_three.setBackgroundColor(Color.GREEN);
}
else{
allAnswersCorrect = false;
et_one_three.setBackgroundColor(Color.RED);
}
if(allAnswersCorrect) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
});
}
}
In my Layout I use ScrollView:
<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" tools:context=".MainActivity"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView2" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/task1"
android:id="#+id/textView1"
android:textSize="20sp"
android:textColor="#010101" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_one"
android:id="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_one"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_two"
android:id="#+id/textView3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_two"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_three"
android:id="#+id/textView4" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_three"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_four"
android:id="#+id/textView5" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_four"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="15dp"
android:textSize="20sp"
android:text="#string/one_five"
android:id="#+id/textView6" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et_one_five"
android:inputType="textCapSentences"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
android:id="#+id/buttonCheck" />
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
I would strongly suggest a nice library called Butterknife by JakeWharton :
http://jakewharton.github.io/butterknife/
In your case your code would look like this :
public class MainActivity extends AppCompatActivity {
#Bind(R.id.et_one_one) EditText et_one_one;
#Bind(R.id.et_one_two) EditText et_one_two;
#Bind(R.id.et_one_three) EditText et_one_three;
#Bind(R.id.buttonCheck) Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
...
}
#OnClick(R.id.submit)
public void submit(View view) {
// check code here
}
Also you can group all your edit texts in a group :
#Bind({ R.id.et_one_one, R.id.et_one_two, R.id.et_one_three })
List<EditText> nameViews;
And apply some setters or actions on them :
...
ButterKnife.apply(nameViews, LOWERCASE);
...
static final ButterKnife.Action<View> LOWERCASE= new ButterKnife.Action<View>() {
#Override public void apply(View view, int index) {
// TODO set the text of the view to lowercase and disable textview
}
};
You can use RecyclerView to implement this. With it, you can dynamically add as much EditText for cars as you want. The sample is shown as below:
In your Activity:
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private String[] answerArray;
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
answerArray = new String[]{
"maserati",
"mercedes",
"bmw"
... (you can add as much as you want)
}
buttonCheck = (Button) findViewById(R.id.buttonCheck);
}
For RecyclerView.Adapter
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> {
String[] mAnswerArray;
public static class ViewHolder extends RecyclerView.ViewHolder {
public EditText editText;
public ViewHolder(View v) {
super(v);
editText = (EditText) v.findViewById(R.id.editText);
}
}
public MyRecyclerAdapter(String[] answerArray) {
this.mAnswerArray = answerArray;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position){
super.onBindViewHolder(holder, position);
final String answer = mAnswerArray.get(position);
if ( holder.editText.getText().toString().toLowerCase().equals(answer) ) {
holder.editText.setBackgroundColor(Color.GREEN);
} else {
holder.editText.setBackgroundColor(Color.RED);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_list_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public int getItemCount() {
return mAnswerArray.size();
}
}
For "my_list_item.xml", you just need to put inside and as for the ButtonCheck you can also pass an array or flag into adapter to record the state of each answer (correct or wrong) in order to decide whether to go to SecondActivity.

Categories

Resources