android spinner setSelection not working even after call setAdapter - android

I have this strange behavior, I have class that extend Dialog, and in onCreate() Method I load data and set it to my spinner and then call spinner.setSelection , the spinner is always select the first item.
I have tried
spinner.setSelection(position);
spinner.setSelection(position, true);
spinner.setSelection(position, false);
spinner.post (Runnable)
new Handler().postDelay (Runnable)
so please can any one tell me what is the problem ??
EDIT
public class MyDialog extends Dialog{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
int layourResId = mContext.getResources().getIdentifier("dialog_layout_default", "layout", mContext.getPackageName());
setContentView(layourResId);
initializeUIComponent();
initializeUIComponentData();
initializeUIComponentAction();
}
private void initializeUIComponent () {
mCountriesSpinner = (Spinner) findViewById(countriesResId);
mOperatorsSpinner = (Spinner) findViewById(operatorsResId);
}
private void initializeUIComponentData () {
mCountriesSpinner.setAdapter(getCountriesAdapter());
mOperatorsSpinner.setAdapter(getOperatorsAdapter(getCountriesAdapter().getItem(mCurrentSelectedCountry)));
mMCC = PhoneUtils.getDeviceMCC(mContext);
mMNC = PhoneUtils.getDeviceMNC(mContext);
if (mMCC != null && mMNC != null) {
String plmn = mMCC + mMNC;
plmn = "41503";
getDefaultSelection(plmn);
}
}
private ArrayList<String> getCountries() {
// logic here
return countriesArray;
}
private ArrayList<String> getOperators(String countryName) {
// logic here
return operatorsArray;
}
private ArrayAdapter<String> getCountriesAdapter() {
// logic here
return countriesArrayAdapter;
}
private ArrayAdapter<String> getOperatorsAdapter(String countryName) {
// logic here
return operatorsArrayAdapter;
}
private void getDefaultSelection(String plmn) {
for (int i = 0; i < array.size(); i++) {
if (array.get(i).getPLMN().equals(plmn)) {
object defaultSelection = array.get(i);
if (defaultSelection != null) {
mCountriesSpinner.setSelection(getCountriesAdapter().getPosition(defaultSelection.getCountryName()));
ArrayAdapter<String> adapter = getOperatorsAdapter(defaultSelection.getCountryName());
mOperatorsSpinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
int position = adapter.getPosition(defaultChannel.getOperatorName());
Toast.makeText(mContext, "position to be selected in operator " + position, Toast.LENGTH_SHORT).show();
mOperatorsSpinner.setSelection(position, true);
}
}
}
}
}
EDIT2
<RelativeLayout 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"
android:background="#android:color/transparent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/default_container_bg"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="#string/please_choose_country"
android:textColor="#android:color/black" />
<Spinner
android:id="#+id/countries_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="#string/please_choose_operator"
android:textColor="#android:color/black" />
<Spinner
android:id="#+id/operators_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<Button
android:id="#+id/payment_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="#string/payment" />
</LinearLayout>
</RelativeLayout>

Related

Can't set RecyclerView inside CardView?

I'm trying to put a RecyclerView inside a CardView and create items dynamically.
Obviously, in XML, RecyclerView is set inside CardView tag, but as you can see picture, RecyclerView item is created outside CardView.
(RecyclerView's items are the parts expressed as kg and set in the photo. And CardView is also an item of another RecyclerView.)
What's the problem?
XML
<androidx.cardview.widget.CardView
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="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="12dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
app:cardElevation="10dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/ll1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/workout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="TEST"/>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/light_blue_400"/>
</LinearLayout>
<LinearLayout
android:id="#+id/ll2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#+id/ll1">
<com.google.android.material.button.MaterialButton
android:id="#+id/delete"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="8dp"
android:layout_marginEnd="4dp"
style="#style/RoutineButtonStyle"
android:text="DELETE"
app:icon="#drawable/ic_delete"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="4dp"
android:layout_marginEnd="8dp"
style="#style/RoutineButtonStyle"
android:text="ADD"
app:icon="#drawable/ic_add"/>
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/ll2"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
Let me know if you need any other code.
Here is the Activity of your add/delete CardView:
//Item List if you want to add one or more Items
private List<MyItem> myItems = new ArrayList<>();
private Adapter smallCardAdapter;
private int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.rv);
//Creates a new Object in the Adapter.class
smallCardAdapter = new Adapter();
recyclerView.setAdapter(smallCardAdapter);
CardView cardView = findViewById(R.id.cardView);
MaterialButton delete = findViewById(R.id.delete);
MaterialButton add = findViewById(R.id.add);
//Add onClickListener
add.setOnClickListener(v -> {
try {
size = myItems.size();
//if the value is 0, a new item is created
//if you want to delete the card after 0 than you have to change the value to 0
if(size == 0){
//Creates a new Object in the MyItem.class
myItems.add(new MyItem("Set","1kg"));
}else{
MyItem myItem = myItems.get(0);
//Replace kg with "" to make a Integer
String secondString = myItem.getSecondString().replace("kg","");
Integer value = Integer.valueOf(secondString);
value++;
myItem.setSecondString(value+"kg");
myItems.set(0,myItem);
}
updateAdapter();
}catch (Exception e){
Log.w("MainActivity","Add Button OnClickListener");
e.printStackTrace();
}
});
//Delete onClickListener
delete.setOnClickListener(v->{
try {
size = myItems.size();
//If the value is 0 then canceled to avoid errors
if(size == 0){
return;
}
MyItem myItem = myItems.get(0);
//Replace kg with "" to make a Integer
String secondString = myItem.getSecondString().replace("kg","");
Integer value = Integer.valueOf(secondString);
//if the value is one or lower
if(value <= 1){
//The card will deleted after updateAdapter();
myItems.clear();
}else{
value--;
myItem.setSecondString(value+"kg");
myItems.set(0,myItem);
}
updateAdapter();
}catch (Exception e){
Log.w("MainActivity","Delete Button OnClickListener");
e.printStackTrace();
}
});
}
private void updateAdapter(){
try {
smallCardAdapter.setItems(myItems);
}catch (Exception e){
Log.w("MainActivity","updateAdapter");
e.printStackTrace();
}
}
The custom Item called MyItem:
public class MyItem {
String firstString;
String secondString;
public MyItem(String firstString,String secondString){
this.firstString = firstString;
this.secondString = secondString;
}
public String getFirstString() {
return firstString;
}
public void setFirstString(String firstString) {
this.firstString = firstString;
}
public String getSecondString() {
return secondString;
}
public void setSecondString(String secondString) {
this.secondString = secondString;
}
}
The Adapter.java creates a smallCard:
public class Adapter extends RecyclerView.Adapter<Adapter.SmallCardHolder> {
private List<MyItem> items = new ArrayList<>();
#NonNull
#Override
public SmallCardHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// I created a new smallcard for the CardView
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.smallcard, parent, false);
SmallCardHolder smallCardHolder = new SmallCardHolder(itemView);
return smallCardHolder;
}
#Override
public void onBindViewHolder(#NonNull final SmallCardHolder holder, int position) {
//get the current item of the position
MyItem myItem = items.get(position);
String firstString = myItem.getFirstString();
String secondString = myItem.getSecondString();
holder.textViewSet.setText(firstString);
holder.textViewkg.setText(secondString);
}
#Override
public int getItemCount () {
return items.size();
}
public void setItems(List <MyItem> items) {
this.items = items;
notifyDataSetChanged();
}
class SmallCardHolder extends RecyclerView.ViewHolder {
//Here are the TextView's of the smallcard (smallcard.xml)
private TextView textViewSet;
private TextView textViewkg;
public SmallCardHolder(#NonNull View itemView) {
super(itemView);
textViewSet = itemView.findViewById(R.id.set);
textViewkg = itemView.findViewById(R.id.kg);
}
}
}
Create a new layout with name called smallcard.xml for the Adapter.java:
<?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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/set"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"
android:layout_centerVertical="true"
android:textSize="18sp"
android:layout_marginStart="5dp"
android:textColor="?attr/colorPrimary"
android:textStyle="bold"/>
<TextView
android:id="#+id/kg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="kg"
android:layout_toRightOf="#id/set"
android:layout_marginLeft="55dp"
android:layout_centerVertical="true"
android:textColor="?attr/colorPrimary"
android:textSize="16sp"
android:layout_marginRight="10dp"
android:maxLines="1"/>
</RelativeLayout>
</RelativeLayout>
In your XML you have to give the CardView a name. I called it cardView. Here is the code android:id="#+id/cardView"
Result:
You will find more information as comments in the code.

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();
}
});

List item click listener inside a Fragment

I am trying to change the text and check box response of the clicked list item but I am not able to do so. As I not able to get the click list item.
The fragment is a part of view pager.
Here is my code,
public class ParticipantsFragment extends Fragment {
private ParticipantAdapter mAdapter;
SwipeRefreshLayout refreshLayout;
private String mParticipantId, mEventId, mGender;
ParticipantsAsyncTask task;
public ParticipantsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEventId = getArguments().getString(Config.BUNDLE_KEY_EVENT_ID);
mParticipantId = getArguments().getString(Config.BUNDLE_KEY_PARTICIPANT_ID);
mGender = getArguments().getString(Config.BUNDLE_KEY_GENDER);
Log.v("fragh", mEventId + " " + mParticipantId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.participant_list, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.no_participant);
task = new ParticipantsAsyncTask();
task.execute();
ListView participantListView = (ListView) rootView.findViewById(R.id.participant_list);
refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout_participant_list);
participantListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.v("Clicked Participant",mAdapter.getItem(position).getParticipantName());
EditText notes = (EditText) rootView.findViewById(R.id.participant_list_item_notes);
String text = notes.getText().toString();
Log.v("Participant Text",text);
CheckBox checkBox = (CheckBox) rootView.findViewById(R.id.participant_list_item_checkbox);
String check;
if(checkBox.isChecked())
{
check = "1";
}
else
{
check = "0";
}
}
});
Button submit = (Button) rootView.findViewById(R.id.submit_participant);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mAdapter = new ParticipantAdapter(getContext(), new ArrayList<Participant>());
participantListView.setAdapter(mAdapter);
participantListView.setEmptyView(textView);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
task = new ParticipantsAsyncTask();
task.execute();
refreshLayout.setRefreshing(false);
}
});
return rootView;
}
private class ParticipantsAsyncTask extends AsyncTask<Void, Void, List<Participant>> {
private ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = new ProgressDialog(getContext());
progress.setMessage("Gathering Data...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
}
#Override
protected void onPostExecute(List<Participant> data) {
// Clear the adapter of previous participant data
mAdapter.clear();
// If there is a valid list of {#link Event}s, then add them to the adapter's
// data set. This will trigger the ListView to update.
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
#Override
protected List<Participant> doInBackground(Void... params) {
List<Participant> result;
if (!mGender.isEmpty()) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(Config.KEY_EVENT_ID, mEventId);
map.put(Config.KEY_PARTICIPANT_ID, mParticipantId);
map.put(Config.KEY_GENDER, mGender);
result = QueryUtils.extractParticipantData(map, Config.FEVER_GENDER_FILTER_PARTICIPANT_URL);
} else {
HashMap<String, String> map = new HashMap<String, String>();
map.put(Config.KEY_EVENT_ID, mEventId);
map.put(Config.KEY_PARTICIPANT_ID, mParticipantId);
Log.v("law", mEventId + ", " + mParticipantId);
result = QueryUtils.extractParticipantData(map, Config.FEVER_ALL_PARTICIPANT_URL);
}
progress.dismiss();
return result;
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
mAdapter.clear();
}
}
participant_list.xml
<?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:orientation="vertical">
<TextView
android:id="#+id/no_participant"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:gravity="center_horizontal"
android:text="#string/no_participant_found"
android:textColor="#color/primaryText"
android:textSize="24sp"
android:visibility="gone" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout_participant_list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ListView
android:id="#+id/participant_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/divider"
android:dividerHeight="1dp"
android:descendantFocusability="beforeDescendants"
android:drawSelectorOnTop="true"
android:headerDividersEnabled="true" />
</android.support.v4.widget.SwipeRefreshLayout>
<Button
android:id="#+id/submit_participant"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit"
android:textSize="20sp"
android:background="#color/colorAccent"/>
</LinearLayout>
participant_list_item.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="80dp"
android:clickable="true"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:orientation="horizontal"
android:padding="8dp">
<TextView
android:id="#+id/participant_list_item_id"
android:layout_width="0dp"
android:textStyle="bold"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="2"
android:textSize="20sp"
tools:text="M78" />
<TextView
android:id="#+id/participant_list_item_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_weight="5"
android:textSize="20sp"
android:fontFamily="sans-serif"
tools:text="Billu Barber" />
<EditText
android:id="#+id/participant_list_item_notes"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_weight="6"
android:textSize="12sp"
android:background="#drawable/participant_list_notes"
android:hint="#string/participant_notes"
android:inputType="textMultiLine"
android:scrollbars="none"
android:imeOptions="actionDone"
android:maxLength="50"
android:padding="4dp" />
<CheckBox
android:id="#+id/participant_list_item_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp" />
</LinearLayout>
My guess is that at the AdapterView.OnItemClickListener you are using rootView to access the cell properties. Like:
EditText notes = (EditText) rootView.findViewById(R.id.participant_list_item_notes);
...
CheckBox checkBox = (CheckBox) rootView.findViewById(R.id.participant_list_item_checkbox);
You should use the parameter View view from onItemClick like that:
EditText notes = (EditText) view.findViewById(R.id.participant_list_item_notes);
...
CheckBox checkBox = (CheckBox) view.findViewById(R.id.participant_list_item_checkbox);
Let me know if it solves your problem.
Edit:
If the problem is having the item clicked, check https://stackoverflow.com/a/20755698/2174489

Why the recycler view doesn't work with load more functionality?

When execute code that time, null pointer coming, I can't understand what to do next?
activity_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.siliconinfo.loadmoredemo.MainActivity">
<Button
android:id="#+id/openFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click to open" />
<FrameLayout android:id="#+id/contain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey_dark"
xmlns:android="http://schemas.android.com/apk/res/android">
</FrameLayout>
</LinearLayout>
fragment_product.xml
<?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:orientation="vertical">
<LinearLayout
android:id="#+id/filterSortLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white_dim_filter"
android:visibility="gone"
android:orientation="horizontal">
<TextView
android:id="#+id/filterProductLsit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableLeft="#mipmap/ic_filter_icon"
android:drawablePadding="#dimen/margin_10"
android:gravity="center_vertical"
android:padding="#dimen/margin_5"
android:text="#string/filter_text"
android:textColor="#color/grey_dark"
android:textSize="#dimen/drawer_subheader" />
<TextView
android:id="#+id/sortProductList"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="#dimen/margin_5"
android:drawableLeft="#mipmap/ic_sort_icon"
android:drawablePadding="#dimen/margin_10"
android:gravity="center_vertical"
android:padding="#dimen/margin_5"
android:text="#string/sort_text"
android:textColor="#color/grey_dark"
android:textSize="#dimen/drawer_subheader" />
<ImageView
android:id="#+id/gridListToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="#dimen/activity_horizontal_margin"
android:src="#mipmap/gri_view_icon" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#color/skyblue_view" />
<TextView
android:id="#+id/noDataMessageText"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/no_item_found"
android:visibility="gone" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#mipmap/bestsellers_mainbg">
<ProgressBar
android:id="#+id/progressBarItemsRecycler"
style="?android:progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<android.support.v7.widget.RecyclerView
android:id="#+id/productListRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white_dim_details"
android:fitsSystemWindows="true"
android:visibility="gone" />
<ProgressBar
android:id="#+id/progressBarItemsRecyclerOuter"
style="?android:progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
</FrameLayout>
</LinearLayout>
row layout set in adapter
row_gridviewtype.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#mipmap/bestsellers_pro_listbg"
android:orientation="vertical"
android:padding="#dimen/margin_5">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<ProgressBar
android:id="#+id/progressBarItems"
style="?android:progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<ImageView
android:id="#+id/imageview"
android:layout_width="#dimen/row_accessories_grid_width"
android:layout_height="#dimen/row_accessories_grid_width_hight"
android:src="#mipmap/no_image_available"
android:layout_gravity="center_horizontal" />
</FrameLayout>
<TextView
android:id="#+id/productNameText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:singleLine="true"
android:textSize="#dimen/text_header" />
<TextView
android:id="#+id/productPriceText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingBottom="#dimen/margin_5"
android:paddingTop="#dimen/margin_5"
android:singleLine="true"
android:textColor="#color/skyblue_view"
android:textSize="#dimen/text_header" />
<TextView
android:id="#+id/productRegularPriceText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingBottom="#dimen/margin_5"
android:paddingTop="#dimen/margin_5"
android:singleLine="true"
android:textColor="#color/grey"
android:textSize="#dimen/text_header" />
</LinearLayout>
This is progressbar , load below the recyclerview, when scroll a recycler view.
row_load.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_gravity="center_horizontal" />
</LinearLayout>
DesktopFragment cointain list
public class DeskPortTprtOurFvtAromaThrpyFragment extends Fragment implements View.OnClickListener {
private static String TAG ="DeskPortTprtOurFvtAromaThrpyFragment";
private View mRoot;
private SharedPreferences mPreferences;
private Typeface mTypefaceBold,mTypefaceSemiBold,mTypefaceRegular;
private RecyclerView mProductListRecyclerView;
privateArrayList<ProductListResponseModel>
mProductListResponseModelArrayList = new ArrayList<ProductListResponseModel>();
private ProgressBar mProgressBarRecycleView, mProgressBarOuter;
private boolean mVieType = true;
private String
mProductResponsePortableStr,mProductResponseDesktopStr,
mProductResponseTopRatedStr,mProductResponseOurFavouriteStr,
mProductResponseAromaTherapyStr, mCategoryStr;
String pageNumber = "", shortValue = "", storeId = "", shopByFrom= "", shopByTo = "";
private TextView mFilterTextView, mSortTextView;
private ArrayList<String> categoryID = new ArrayList<String>();
ArrayList<String> mCAtegoryIdFilter = new ArrayList<String>();
private String shopByFrom1 = "", shopByFrom2 = "", shopByFrom3="", shopByTo1 = "", shopByTo2 = "", shopByTo3 = "";
View.OnClickListener mFilterClickListener;
private String mFilterTag = "NO";
private boolean zeroPosition = false, onePosition = false, secondPositon = false, thirdPosition = false;
String pageNo = "0";
private ImageView mToggleViewListGridImageView;
Bundle productID;
ProductListAdaptr mProductListAdaptr;
private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.fragment_product, container,false);
initView();
return mRoot;
}
private void initView() {
mPreferences = getActivity().getSharedPreferences(Utils.PREF_NAME, Context.MODE_PRIVATE);
mToggleViewListGridImageView = (ImageView)mRoot.findViewById(R.id.gridListToggle);
((ImageView)mRoot.findViewById(R.id.gridListToggle)).setOnClickListener(this);
mProductListRecyclerView = (RecyclerView) mRoot.findViewById(R.id.productListRecyclerView);
mFilterTextView = (TextView) mRoot.findViewById(R.id.filterProductLsit);
mSortTextView = (TextView) mRoot.findViewById(R.id.sortProductList);
((TextView) mRoot.findViewById(R.id.filterProductLsit)).setOnClickListener(this);
((TextView) mRoot.findViewById(R.id.sortProductList)).setOnClickListener(this);
Logger.e("TAG", "Product ID is : " + categoryID);
mProgressBarRecycleView = (ProgressBar) mRoot.findViewById(R.id.progressBarItemsRecycler);
mProgressBarOuter = (ProgressBar) mRoot.findViewById(R.id.progressBarItemsRecyclerOuter);
categoryID.add("10");
mProductListAdaptr = new ProductListAdaptr(getContext(), mProductListResponseModelArrayList, mProductClickListener, 0);
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
mProductListRecyclerView.setLayoutManager(linearLayoutManager);
mProductListRecyclerView.setItemAnimator(new DefaultItemAnimator());
mProductListAdaptr.setLoadMoreListener(new ProductListAdaptr.OnLoadMoreListener() {
#Override
public void onLoadMore() {
mProductListRecyclerView.post(new Runnable() {
#Override
public void run() {
int index = mProductListResponseModelArrayList.size() - 1;
loadMore(index);
}
});
}
});
load(0);
}
private void load(int index) {
getProductList(categoryID, String.valueOf(index), "", "", "", "", "", "", "", "", "");
}
private void loadMore(int index) {
}
private void showProductList() {
((LinearLayout) mRoot.findViewById(R.id.filterSortLayout)).setVisibility(View.VISIBLE);
((TextView) mRoot.findViewById(R.id.noDataMessageText)).setVisibility(View.GONE);
mProductListRecyclerView.setVisibility(View.VISIBLE);
if (mVieType == true) {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
mProductListRecyclerView.setLayoutManager(linearLayoutManager);
ProductListRecyclerView.setItemAnimator(newDefaultItemAnimator());
mProductListRecyclerView.setAdapter(new ProductListAdaptr(getContext(), mProductListResponseModelArrayList, mProductClickListener, 0));
} else if (mVieType == false) {
final GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
mProductListRecyclerView.setLayoutManager(mLayoutManager);
mProductListRecyclerView.setItemAnimator(new DefaultItemAnimator());
mProductListRecyclerView.setAdapter(new ProductListAdaptr(getContext(), mProductListResponseModelArrayList, mProductClickListener, 1));
}
mProductListResponseModelArrayList.addAll(mProductListResponseModelArrayList);
mProductListAdaptr.notifyDataChanged();
}
private View.OnClickListener mProductClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
}
};
private void getProductList(ArrayList<String> categoryId, String pagenumber, String shopByFrom1, String shopByTo1,
String shopByFrom2, String shopByTo2, String shopByFrom3, String shopByTo3, String shortValue, String storesID, String FilterTag) {
String categoryListString = "";
for (int i = 0; i < categoryId.size(); i++) {
if (i == 0)
categoryListString = categoryId.get(i).toString();
else
categoryListString = categoryListString + ", " + categoryId.get(i).toString();
}
if (Utils.checkInternetConnection(getActivity())) {
final ProdcutListRequestTask mProductListRequestTask = new ProdcutListRequestTask(getActivity());
mProductListRequestTask.setAsyncCallListener(new AsyncCallListener() {
#Override
public void onResponseReceived(Object response) {
mProductListResponseModelArrayList (ArrayList<ProductListResponseModel>) response;
((LinearLayout)mRoot.findViewById(R.id.filterSortLayout)).setVisibility(View.VISIBLE);
mProgressBarOuter.setVisibility(View.GONE);
mProgressBarRecycleView.setVisibility(View.GONE);
if (mProductListResponseModelArrayList != null) {
Logger.e(TAG, "DektoPportaOurFavouriteFragment : " + mProductListResponseModelArrayList.size());
}
if (response == null) return;
if (mProductListResponseModelArrayList == null || mProductListResponseModelArrayList.size() == 0) {
((TextView) mRoot.findViewById(R.id.noDataMessageText)).setTypeface(mTypefaceBold);
((TextView) mRoot.findViewById(R.id.noDataMessageText)).setVisibility(View.VISIBLE);
((LinearLayout) mRoot.findViewById(R.id.filterSortLayout)).setVisibility(View.GONE);
return;
}
showProductList();
}
#Override
public void onErrorReceived(String error) {
mProgressBarOuter.setVisibility(View.GONE);
}
});
mProductListRequestTask.execute(categoryListString, pagenumber, shopByFrom1, shopByTo1, shopByFrom2, shopByTo2, shopByFrom3, shopByTo3,
shortValue, storesID, FilterTag);
} else {
Toast.makeText(getActivity(), getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
mProgressBarOuter.setVisibility(View.GONE);
}
}
}
use this, working for me.
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (hasMore && !(hasFooter())) {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
//position starts at 0
if (layoutManager.findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 2) {
new GetPostData().execute();
}
}
else{
}
}
});
hope it will also help you.

How to loop execution of AsyncTask with an array of params

I'm new in Android programming.
I created classes of web objects each class has 3 RSS URLs to be parsed. I loop an array of this objects to operate on each one the AsyncTask Executer. Every time I do that different errors appear and the UI freezes. I can't find what's wrong. Then I use custom adapter to display the UI but program don't even reach to that code. Please help me finding what's wrong with my code. I tried everything I had in mind.
I loop it in the main thread like this:
public class MainActivity extends Activity
{
ArrayList <WebPage> wpObjects;
ListView lv;
int threadIsFinishedcounter=0;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.listView1);
WebPage ynet= new WebPage(R.drawable.ynet, "http://www.ynet.co.il/Integration/StoryRss2.xml","http://www.ynet.co.il/Integration/StoryRss6.xml","http://www.ynet.co.il/Integration/StoryRss3.xml");
WebPage walla=new WebPage(R.drawable.walla, "http://rss.walla.co.il/?w=/1/0/12/#rss.e","http://rss.walla.co.il/?w=/2/0/12/#rss.e","http://rss.walla.co.il/?w=/3/0/12/#rss.e");
WebPage nrg= new WebPage(R.drawable.nrg, "http://rss.nrg.co.il/news/","http://rss.nrg.co.il/finance","http://rss.nrg.co.il/sport");
wpObjects=new ArrayList<WebPage>();
wpObjects.add(ynet);
wpObjects.add(walla);
wpObjects.add(nrg);
for(WebPage item:wpObjects)
{
//new getParseData(wpObjects.indexOf(item)).execute(item.getUrls());
new getParseData(wpObjects.indexOf(item)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, item.getUrls());
}
if(threadIsFinishedcounter==wpObjects.size())
{
MyCostumedAdapter adapter=new MyCostumedAdapter(MainActivity.this, wpObjects);
lv.setAdapter(adapter);
if(threadIsFinishedcounter==wpObjects.size())
}
}
The AsyncTask class:
class getParseData extends AsyncTask<String,Void, Collecter>
{
int indexofwp;
public getParseData(int indexofwp) {
super();
this.indexofwp = indexofwp;
}
protected Collecter doInBackground(String... params) {
Collecter col = new Collecter() ;
ArrayList<String> allResult = new ArrayList<String>();
ArrayList<String> Titles = new ArrayList<String>();
for (int y = 0; y < params.length; y++) {
Titles.clear();
allResult.clear();
col.yIndex = y;
String urlString = params[y];
try {
URL url = new URL(urlString);
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
XmlPullParser parser = factory.newPullParser();
InputStream is = url.openStream();
parser.setInput(is, null);
boolean inItemTag = false;
boolean inTitleTag = false;
String TagName;
int EventType = parser.getEventType();
while (EventType != XmlPullParser.END_DOCUMENT) {
Log.i("im in while loop of parser", "");
if (EventType == XmlPullParser.START_TAG) {
TagName = parser.getName();
if (inItemTag) {
if (TagName.equals("title"))
inTitleTag = true;
} else// !item
{
if (TagName.equals("item"))
inItemTag = true;
}
}
if (EventType == XmlPullParser.TEXT) {
if (inTitleTag) {
Titles.add(parser.getText());// AD THE TITLE
inTitleTag = false;
}
}
if (EventType == XmlPullParser.END_TAG) {
TagName = parser.getName();
if (TagName.equals("item"))
inItemTag = false;
}
EventType = parser.next();
Log.i("im after parser.next", "");
}// end while of parsing loop
} catch (MalformedURLException e) {
e.printStackTrace();
Log.i("EXEPTION******************",
"MalformedURLException*********");
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.i("EXEPTION******************",
"XmlPullParserException*********");
} catch (IOException s) {
s.printStackTrace();
Log.i("IOException***************************", "");
}
synchronized (col) {
if (col.yIndex == 0) {
col.news.addAll(Titles);
col.rssRsult.add(col.news);
}
if (col.yIndex == 1) {
col.economy.addAll(Titles);
col.economy.size()+"");
col.rssRsult.add(col.economy);
}
if (col.yIndex == 2) {
col.sports.addAll(Titles);
col.sports.size()+"");
col.rssRsult.add(col.sports);
}
}
}// end of y loop
return col;
}
#Override
protected void onPreExecute()
{
if(threadIsFinishedcounter==wpObjects.size())
threadIsFinishedcounter=0;
}
#Override
protected void onPostExecute(Collecter coll)
{
if(indexofwp<wpObjects.size())
{
wpObjects.get(indexofwp).NewsTitles.addAll(coll.rssRsult.get(0));
wpObjects.get(indexofwp).EconomicsTitles.addAll(coll.rssRsult.get(1))
wpObjects.get(indexofwp).SportssTitles.addAll(coll.rssRsult.get(2));
threadIsFinishedcounter++;
}
I thought maybe my custom adapter is wrong but didn't find anything wrong:
public class MyCostumedAdapter extends BaseAdapter
{
Context context;
ArrayList<WebPage> wp;
public MyCostumedAdapter(Context context , ArrayList<WebPage> wp)
{
super();
this.context = context;
this.wp=wp;
}
#Override
public int getCount()
{
return wp.size();
}
#Override
public Object getItem(int position)
{
return wp.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View rowView;
if(convertView==null)
{
LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView= inflater.inflate(R.layout.lvlayout, null);
}
else
{
final WebPage currentwp=wp.get(position);
rowView=convertView;
ImageView imag=(ImageView)rowView.findViewById(R.id.imageView1);
imag.setImageResource(currentwp.getIcon());
Button newsButton=(Button)rowView.findViewById(R.id.AllnewsButton);
newsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent=new Intent(context,NewHeadlines.class);
intent.putExtra("newsbutton",currentwp.getNewsTitles());//to pass information to next activity
context.startActivity(intent);
}
});
Button economicsButton=(Button)rowView.findViewById(R.id.AllEconomicsButton);
economicsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent=new Intent(context,NewHeadlines.class);
intent.putExtra("economicbutton",currentwp.getEconomicsTitles());//to pass information to next activity
context.startActivity(intent);
}
});
Button sportsButton=(Button)rowView.findViewById(R.id.AllSportsButton);
sportsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent=new Intent(context,NewHeadlines.class);
intent.putExtra("sportsbutton",currentwp.getSportssTitles());//to pass information to next activity
context.startActivity(intent);
}
});
TextView firstNewsTitle=(TextView)rowView.findViewById(R.id.firstnewsTitle);
firstNewsTitle.setText(currentwp.getNewsTitles().get(0));
TextView firstEconomicsTitle=(TextView)rowView.findViewById(R.id.firsteconomicsTitle);
firstEconomicsTitle.setText(currentwp.getEconomicsTitles().get(0));
TextView firstSportsTitle=(TextView)rowView.findViewById(R.id.firstSportsTitle);
firstSportsTitle.setText(currentwp.getSportssTitles().get(0));
}
return rowView;
}
}
main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="326dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllnewsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/News" />
<TextView
android:id="#+id/firstnewsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllEconomicsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Economic" />
<TextView
android:id="#+id/firsteconomicsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllSportsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Sports" />
<TextView
android:id="#+id/firstSportsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout >
</LinearLayout >
each ListView row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="326dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllnewsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/News" />
<TextView
android:id="#+id/firstnewsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/AllEconomicsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Economic" />
<TextView
android:id="#+id/firsteconomicsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
< Button
android:id="#+id/AllSportsButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Sports" />
< TextView
android:id="#+id/firstSportsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
You should pass your array inyo the constructor and then operate and handle that there. I am sure that you can send your array into your params, but you should make your Asynktask diferent fr string values, as currently you have. So the easy and best way is :
int indexofwp;
List<String> allResult = new ArrayList<String>()
public getParseData(int indexofwp, List<String> allResult)
{
super();
this.indexofwp = indexofwp;
This.allResult=allResult;
}
And thats all.
Regards.

Categories

Resources