The data in my ListView is not refreshed until I press my EditText

0

I hope you can help me, you will see I have a hamburger menu which loads in its main activity a FRAGMENT with a LISTVIEW and an EDIT TEXT (to search the list), When it starts it fills up normally and shows the info ok, BUT when in the side menu of my hamburger menu I select another item to change the fragment which contains the same LISTVIEW and an EDITTEXT does not show the info of the list UNTIL I press EDITTEXT.

I HOPE YOU CAN HELP ME. PS: the list is filled by consuming a service and I use an adapter to customize my items.

MainActivity class:

package jonathanc.ygo_card_finder;

import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import jonathanc.ygo_card_finder.card_list.cardListFragment;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    /*FloatingActionButton fab = (FloatingActionButton)  findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",   Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
*/
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    cardListFragment nuevoFragmento = new cardListFragment();
   // expansionListFragment nuevoFragmento= new expansionListFragment();
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.main_container, nuevoFragmento);
    transaction.commit();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
 }

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {
        expansionListFragment nuevoFragmento= new expansionListFragment();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.main_container, nuevoFragmento);
        transaction.commit();
    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
 }
}

ExpansionListFragment class:

package jonathanc.ygo_card_finder;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import jonathanc.ygo_card_finder.card_info.ContainerActivity;
import jonathanc.ygo_card_finder.card_list.carta;
import jonathanc.ygo_card_finder.card_list.cartaAdapter;

/**
  * A simple {@link Fragment} subclass.
  */
 public class expansionListFragment extends Fragment implements   AdapterView.OnItemClickListener {

ArrayList<cardSet> setsArrayList = new ArrayList();
ListView listView;
EditText editText;
Activity activity = getActivity();
ProgressDialog progressDialog;
cardSetAdapter setsAdapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_expansion_list, container, false);

    return view;
}

@Override
public void onActivityCreated(Bundle state) {
    super.onActivityCreated(state);
    pinta();
}

private void pinta() {
    listView = getView().findViewById(R.id.lista);
//        sv=findViewById(R.id.searchView1);

    RequestQueue queue = Volley.newRequestQueue(getActivity());
    String url = "http://yugiohprices.com/api/card_sets";
    progressDialog = new ProgressDialog(getContext());
    progressDialog.setCancelable(false);
    progressDialog.setMessage("Cargando la lista de sets existentes");
    progressDialog.show();

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @SuppressLint("WrongConstant")
                @Override
                public void onResponse(String response) {
                    try {
                        String url_image;
                        String nombreCarta;
                        String respuestaCodificada = new String(response.getBytes("ISO-8859-1"), "UTF-8");
                        JSONArray jsonArray = new JSONArray(respuestaCodificada);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            nombreCarta = jsonArray.get(i).toString();
                            url_image = "http://yugiohprices.com/api/set_image/" + jsonArray.get(i).toString();
                            //Log.v("HOLI", url_image);
                              setsArrayList.add(new cardSet(nombreCarta, url_image));

                        }
                        progressDialog.cancel();


                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }


                }
            }, new Response.ErrorListener()

    {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getContext(), "Woops hubo un problema inesperado!", Toast.LENGTH_SHORT).show();
            progressDialog.cancel();
        }
    });
    queue.add(stringRequest);

    setsAdapter = new cardSetAdapter(getActivity(), setsArrayList);
    listView.setAdapter(setsAdapter);

    listView.setOnItemClickListener(this);

    editText = getView().findViewById(R.id.search);

    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub
            setsAdapter.getFilter().filter(arg0);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }
    });

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    TextView textView = view.findViewById(R.id.tv_name2);//TODO
    /*Intent intent = new Intent(getContext(), ContainerActivity.class);
    intent.putExtra("nombreCarta", textView.getText().toString());
    startActivity(intent);
*/

    Toast.makeText(getContext(), "POSICION : " +  textView.getText().toString(),
            Toast.LENGTH_SHORT).show();
}

}

Class cardSetAdapter:

package jonathanc.ygo_card_finder;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;


public class cardSetAdapter extends BaseAdapter implements Filterable {

public cardSetAdapter(Activity activity, ArrayList<cardSet> setsArray) {
    this.activity = activity;
    this.setsArray = setsArray;
    this.listFiltered = setsArray;

}
cardSetAdapter.CustomFilter filter;
protected Activity activity;
protected ArrayList<cardSet> setsArray;
ArrayList<cardSet> listFiltered;



@Override
public int getCount() {
    return setsArray.size();
}

@Override
public Object getItem(int position) {
    return setsArray.get(position);
}

@Override
public long getItemId(int position) {
    return setsArray.indexOf(getItem(position));    }

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        LayoutInflater inf = activity.getLayoutInflater();
        convertView = inf.inflate(R.layout.sets, null);
    }
    cardSet dir = setsArray.get(position);

    ImageView imageView = convertView.findViewById(R.id.imageView2);
    Picasso.get().load(dir.getImagen()).into(imageView);

    TextView textView = convertView.findViewById(R.id.tv_name2);
    textView.setText(dir.getNombre());

    return convertView;
}
@Override
public Filter getFilter() {
    // TODO Auto-generated method stub
    if(filter == null)
    {
        filter=new cardSetAdapter.CustomFilter();
    }

    return filter;
}

//INNER CLASS
class CustomFilter extends Filter
{

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        // TODO Auto-generated method stub

        FilterResults results=new FilterResults();

        if(constraint != null && constraint.length()>0)
        {
            //CONSTARINT TO UPPER
            constraint=constraint.toString().toUpperCase();

            ArrayList<cardSet> filters=new ArrayList<cardSet>();

            //get specific items
            for(int i=0;i<listFiltered.size();i++)
            {
                if(listFiltered.get(i).getNombre().toUpperCase().contains(constraint))
                {
                    cardSet p=new cardSet(listFiltered.get(i).getNombre(), listFiltered.get(i).getImagen());

                    filters.add(p);
                }
            }

            results.count=filters.size();
            results.values=filters;

        }else
        {
            results.count=listFiltered.size();
            results.values=listFiltered;

        }

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        // TODO Auto-generated method stub

        setsArray=(ArrayList<cardSet>) results.values;
        notifyDataSetChanged();
    }

}
}
    
asked by John Corfish Castle 07.09.2018 в 00:20
source

1 answer

0

Try this, in the Class Class ExpansionListFragment:

//despues de esto:
setsAdapter = new CardSetAdapter(getActivity(), setsArrayList);
listView.setAdapter(setsAdapter);
//notificas
setsAdapter.notifyDataSetChanged();

Even so, you should have a class that extends from FragmentPagerAdapter, that is in charge of the changes between fragments, you should use a ViewPager that contains the ListView, the class should be like this:

public class CategoryAdapter extends FragmentPagerAdapter {

    public CategoryAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new ExpansionListFragment();
            case 1:
                return new ExpansionListFragment();
        }
    }

    @Override
    public int getCount() {
        return 2;
    }
}

To change the fragment use this:

viewPager.setCurrentItem(0);
o este otro viewPager.setCurrentItem(1);

To use it, you must do so, in your MainActivity :

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    FragmentManager fragmentManager = getSupportFragmentManager();
    adapter = new CategoryAdapter(fragmentManager);
    viewPager.setAdapter(adapter);

I can even add a ViewPager.OnPageChangeListener to be able to move from one fragment to another by sliding laterally, or for example change the title above to distinguish them:

viewPager.addOnPageChangeListener(this);

This could be the ViewPager:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    tools:layout_editor_absoluteY="0dp"
    tools:layout_editor_absoluteX="8dp"
    tools:ignore="MissingConstraints">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbarSize="150dp" />
</LinearLayout>

This could be the item layout:

<?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">
    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="@color/colorPrimaryDark"
        android:dividerHeight="0dp" />
</LinearLayout>

And only the item would be missing, which could be like this:

<?xml version="1.0" encoding="utf-8"?><!-- Layout for a single list item -->
<LinearLayout
    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:gravity="center_vertical"
    android:orientation="horizontal">
    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        card_view:cardElevation="3dp"
        card_view:cardCornerRadius="4dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:orientation="horizontal">

        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>
    
answered by 07.09.2018 / 02:55
source