I'm trying to parse a json and return its values in an array, then I want to show it in a listview, the log shows me the result that I want, but it is not showing in my cellphone, I'm missing something that I don't know.
The function that make the SyncTask:
public class SincronizarTask {
private Activity ctx;
public SincronizarTask(Activity applicationContext) {
this.ctx = applicationContext;
}
public void inicia(){
this.syncClientes();
}
private void syncClientes() {
ClientRest mClientesRest = new ClientRest(ctx);
mClientesRest.getClientes(new ClientRest.ClientesRestListener() {
public void clientesReceived(List<ClientesModel> clientes) {
for (int i = 0; i < clientes.size(); i++) {
System.out.println(clientes.get(i).getNome());
}
}
});
}
}
ClienteActivity:
public class ClienteActivity extends SherlockFragment {
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_cliente, container, false);
try {
ClienteViewAdapter ad = new ClienteViewAdapter(this.getActivity(), R.layout.fragment_cliente_item);
ListView lv = (ListView) view.findViewById(R.id.listaClientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TextView clienteId = (TextView) view.findViewById(R.id.clienteId);
TextView clienteNome = (TextView) view.findViewById(R.id.clienteNome);
TextView clienteTipoPessoa = (TextView) view.findViewById(R.id.clienteTipo);
Intent intent = new Intent(getActivity(), ContatosView.class);
//intent.putExtra("id_cliente", clienteId.getText()); // envia o id do cliente para a tela de detalhes
intent.putExtra("nome", clienteNome.getText());
intent.putExtra("tipo_pessoa", clienteTipoPessoa.getText());
startActivity(intent);
}
});
lv.setAdapter(ad);
} catch (Exception e) {
new AlertDialog.Builder(getActivity()).setTitle("Erro").setMessage(e.getMessage()).setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
}).show();
}
return view;
}
ClienteViewAdapter:
public class ClienteViewAdapter extends ArrayAdapter<ClientesModel> {
private final LayoutInflater inflater;
private final int resourceId;
public ClienteViewAdapter(FragmentActivity context, int resource) {
super(context, resource);
this.inflater = LayoutInflater.from(context);
this.resourceId = resource;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ClientesModel cliente = getItem(position);
view = inflater.inflate(resourceId, parent, false);
//TextView tvId = (TextView) view.findViewById(R.id.txtTitle);
TextView tvNome = (TextView) view.findViewById(R.id.clienteNome);
TextView tvTipo = (TextView) view.findViewById(R.id.clienteTipo);
//tvId.setText(String.valueOf(cliente.ge()));
tvNome.setText(cliente.getNome());
tvTipo.setText(cliente.getTipo_pessoa());
return view;
}
}
ClientRest:
JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
List<ClientesModel> clientes = null;
try {
clientes = parseJSON(response);
pDialog.hide();
} catch (JSONException e) {
e.printStackTrace();
}
listener.clientesReceived(clientes);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (pDialog.isShowing()) {
pDialog.hide();
}
error.printStackTrace();
}
}
)
mRequestQueue.add(mJsonObjectRequest);
}
private List<ClientesModel> parseJSON(JSONObject json) throws JSONException {
try {
JSONArray dados = json.getJSONArray("dados");
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i);
ClientesModel mClientesModel = new ClientesModel();
ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();
/* cadastra os dados necessários no objeto no modelo */
mClientesModel.setId(item.optInt("id"));
mClientesModel.setNome(item.optString("nome"));
mClientesModel.setTipo_pessoa(item.optString("tipo_pessoa"));
mClientesModel.setInformacoes_adicionais(item.optString("informacoes_adicionais"));
mClientesModel.setCpf(item.optString("cpf"));
mClientesModel.setCnpj(item.optString("cnpj"));
JSONArray contatos = item.getJSONArray("contatos");
for (int j = 0; j < contatos.length(); j++) {
JSONObject data = contatos.getJSONObject(j);
mClientesContatoModel.setNome(data.optString("nome"));
mClientesContatoModel.setCargo(data.optString("cargo"));
}
arrNews.add(mClientesModel);
arrContatos.add(mClientesContatoModel);
}
} catch (Exception e) {
e.printStackTrace();
}
return arrNews;
}
}
Related
I write this code but not show me anything and in logcat have no error
and I have three classes for this code Adapter, recyclertouchlistener and fragments code...
my code in below
this code for fragment :
public class VerticalRecyclerFragment extends Fragment {
RecyclerView rcVertical;
static ArrayList<Products> productsArrayList = new ArrayList<>();
public VerticalRecyclerFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vertical_recycler,
container, false);
showProduct();
rcVertical = view.findViewById(R.id.rcVertical);
rcVertical.addOnItemTouchListener(new RecyclerTouchListener(getContext(), rcVertical,
new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
ProductActivity.products = productsArrayList.get(position);
startActivity(new Intent(getActivity(), ProductActivity.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
Adapter adapter = new Adapter(productsArrayList, getContext());
rcVertical.setLayoutManager(new LinearLayoutManager(getActivity()));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
return view;
}
public void showProduct() {
final ProgressDialog loader = ProgressDialog.show(getActivity(),
"Get products...", "please wait",
false, false);
StringRequest request = new StringRequest(Request.Method.POST,
Config.getProductsWebApi,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loader.dismiss();
productsArrayList.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
productsArrayList.add(p);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loader.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}}
and i write this code for Adapter in a single class :
public class Adapter extends RecyclerView.Adapter<Adapter.MyHolder> {
ArrayList<Products> ProductsList;
Context context;
public Adapter(ArrayList<Products> productsList, Context context) {
ProductsList = productsList;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.row_layout, parent, false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, final int position) {
Products products = ProductsList.get(position);
holder.txtName.setText(products.getName());
holder.txtPrice.setText("$ " + products.getPrice());
Picasso.get().load(Config.ipValue + "/images/" + products.getPhoto()).into(holder.imgV);
holder.imgV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(AnimationUtils.loadAnimation(context, android
.R.anim.slide_in_left));
}
});
}
#Override
public int getItemCount() {
return ProductsList.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView txtName;
TextView txtPrice;
ImageView imgV;
public MyHolder(View itemView) {
super(itemView);
txtName = itemView.findViewById(R.id.rowTxtProductName);
txtPrice = itemView.findViewById(R.id.rowTxtPrice);
imgV = itemView.findViewById(R.id.rowImgProduct);
}
}}
RecyclerTouchListener :
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView,
final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context,
new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child,rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}}
Please if you know whats the problem help me to debug it...
thank you
You need to notifyDataSetChanged() when you get the response.
Make the adapter as a class field
public class VerticalRecyclerFragment extends Fragment {
RecyclerView rcVertical;
static ArrayList<Products> productsArrayList = new ArrayList<>();
Adapter adapter; // <<< Change here
change the initialization (and every call of the adapter to the class field)
adapter = new Adapter(productsArrayList, getContext()); // <<< Change here
rcVertical.setLayoutManager(new LinearLayoutManager(getActivity()));
rcVertical.setItemAnimator(new DefaultItemAnimator());
rcVertical.setAdapter(adapter);
And finally call notifyDataSetChanged() when you get the response
public void showProduct() {
final ProgressDialog loader = ProgressDialog.show(getActivity(),
"Get products...", "please wait",
false, false);
StringRequest request = new StringRequest(Request.Method.POST,
Config.getProductsWebApi,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loader.dismiss();
productsArrayList.clear();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
productsArrayList.add(p);
}
adapter.notifyDataSetChanged(); // <<< Change here
} catch (JSONException e) {
e.printStackTrace();
}
}
}...
...
}
UPDATE:
add attach the adapter to the RecyclerView when you receive the data
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String id = object.getString("id");
String name = object.getString("name");
String description = object.getString("description");
String price = object.getString("price");
String photo = object.getString("photo");
Products p = new Products(id, name, description, price, photo);
productsArrayList.add(p);
}
Adapter adapter = new Adapter(productsArrayList, getContext()); // <<< Change here
rcVertical.setAdapter(adapter); // <<< Change here
[EDIT] I'm new to android development, so please bear with me. I have two java classes named Join Game, extends to AppCompatActivity and HintList,extends to ArrayAdapter<>. This is connected to a database. So maybe its one of the factors?
For the layout of join game, I have a listview
and for the layout of hintlist I have three textview.
The code goes this way
JoinGame
public class JoinGame extends AppCompatActivity {
ListView list;
String[] itemdescription = {};
String[] itemhints = {};
String[] itemlocasyon = {};
ProgressDialog progress;
View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joingame);
Button schan = (Button)findViewById(R.id.tarascan);
schan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(JoinGame.this,ScanActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
progress = new ProgressDialog(this);
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
RequestFactory.joingameitems(JoinGame.this, RequestFactory.user_id, new RequestCallback<JSONArray>() {
#Override
public void onSuccess(final JSONArray response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
} catch (JSONException e) {
e.printStackTrace();
}
} ////////// below this is the adapter
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
}
});
}
#Override
public void onFailed(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(JoinGame.this, message, Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
HintList
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, null, true);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
}
I actually retrieved the data (here)
E/DB: [{"description":"chinese garter","location":"near Tricycle station","hint":"garter plus chinese"},{"description":"isang pinoy game","location":"near ....","hint":"may salitang baka"},{"description":"\"tinik\"","location":"below...","hint":"may salitang tinik"},{"description":"aka Tinubigan","location":"at the back...","hint":"katunog ng pintero"},{"description":"\"knock down the can\"","location":"near...","hint":"gumagamit ng lata"}]
but it doesnt display on my listview
I dont know anymore what I should do.
I actually tried making this (I added view)
final HintList hladapt = new HintList(JoinGame.this,itemdescription,itemlocasyon,itemhints);
list = (ListView)view.findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
progress.dismiss();
but it will only returns an error of java.lang.NullPointerException: Attempt to invoke virtual method
Change this:
View rowView = inflater.inflate(R.layout.hints_list, null, true);
to:
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
Modify your getView() method to:
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.hints_list, parent, false);
TextView itemDesc2 = (TextView)rowView.findViewById(R.id.itemdescription);
TextView itemHint = (TextView)rowView.findViewById(R.id.itemhint);
TextView itemLocation2 = (TextView)rowView.findViewById(R.id.itemlocation);
itemDesc2.setText(itemDesc[position]);
itemHint.setText(itemHints[position]);
itemLocation2.setText(itemLocation[position]);
return rowView;
}
try adding getCount
#Override
public int getCount() {
return itemHints.length;
}
Try to change your code to this
public class HintList extends ArrayAdapter<String> {
private final Activity context;
private String[] itemDesc = {};
private String[] itemHints = {};
private String[] itemLocation = {};
private LayoutInflater inflater=null;
public HintList(Activity context,String[] itemDesc,String[] itemhints,String[] itemlocation) {
super(context,R.layout.hints_list);
this.context = context;
this.itemDesc = itemDesc;
itemHints = itemhints;
itemLocation = itemlocation;
inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return itemHints.length;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view==null){
view=inflater.inflate(R.layout.hints_list, null, true);
holder = new ViewHolder(view);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
holder.itemDesc2.setText(itemDesc[position]);
holder.itemHint.setText(itemHints[position]);
holder.itemLocation2.setText(itemLocation[position]);
return view;
}
static class ViewHolder{
TextView itemDesc2,itemHint,itemLocation2;
ViewHolder(View view) {
itemDesc2 = (TextView)view.findViewById(R.id.itemdescription);
itemHint = (TextView)view.findViewById(R.id.itemhint);
itemLocation2 = (TextView)view.findViewById(R.id.itemlocation);
}
}
}
My suggestions is create a bean class (DetailsBean), used for setter and getter method, and also the ArrayList (details1).
List<DetailsBean> details1 = new ArrayList<>(); // declare this as global
Then add the bean to below code
public void run() {
RequestFactory.response = response;
itemdescription = new String[response.length()];
itemhints = new String[response.length()];
itemlocasyon = new String[response.length()];
for (int hl = 0; hl < response.length(); hl++){
try{
itemdescription[hl] = ((String)(response.getJSONObject(hl)).get("description"));
itemhints[hl] = ((String)(response.getJSONObject(hl)).get("hint"));
itemlocasyon[hl] = ((String)(response.getJSONObject(hl)).get("location"));
// here the bean
DetailsBean dbean = new DetailsBean(itemDescription, itemhints, itemlocasyon);
details1.add(dbean); // add all the data to details1 ArrayList
HintList hladapt = new HintList(getActivity(), details1);
(ListView)findViewById(R.id.item_hints_and_location);
list.setAdapter(hladapt);
} catch (JSONException e) {
e.printStackTrace();
}
}
Your DetailsBean should looked like this
public class DetailsBean {
private String itemDescription="";
private String itemhints="";
private String itemlocasyon ="";
public DetailsBean(String description, String hints, String itemlocasyon) {
this.itemDescription=description;
.....
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDesription;
}
public String getItemDescription() {
return itemDescription;
}
....
}
Then your HintList
public class HintList extends BaseAdapter{
Activity context;
List<DetailsBean> details;
private LayoutInflater mInflater;
public CustomBaseAdapter(Activity context,List<DetailsBean> details) {
this.context = context;
this.details = details;
}
........
}
Add these Override methods in your adapter
#Override
public int getCount() {
return itemHints.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
I need some help. I am trying to implement the Expandable list view. My problem is that when there are more than 2 children then only group must expand if not text view and button visible on the group layout. Please go through my code and the attached Image. The textview and button are visible when there are more than 2 children also.
Screenshot of the menu
Menu.java
public class SubMenu extends BaseActivity {
String item;
ExpandableListView sec;
Toolbar carttoolbar;
private int lastExpandedPosition = -1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sub_menu);
carttoolbar = (Toolbar) findViewById(R.id.carttoolbar);
setSupportActionBar(carttoolbar);
assert getSupportActionBar() != null;
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
String catname = getIntent().getStringExtra("CatName");
getSupportActionBar().setTitle(catname);
sec = (ExpandableListView) findViewById(R.id.seondlst);
sec.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
sec.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
Intent hello = getIntent();
item = hello.getStringExtra("Catergory");
loaditems();
}
private void loaditems() {
String url = Constant.commonurlyell + "data_standard_item_ind_new.php?rname=standardtakeaway&id=" + item;
Log.d("ITems", url);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonObjectRequest arrayRequest = new JsonObjectRequest(Request.Method.GET, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
ArrayList<Subitem_base> list = new ArrayList<Subitem_base>();
ArrayList<Subitem_base_child> ch_list = new ArrayList<Subitem_base_child>();
try {
JSONArray itemsarray = response.getJSONArray("items");
Map<Integer, ArrayList<Subitem_base_child>> ch_lists = new HashMap<Integer, ArrayList<Subitem_base_child>>();
for (int i = 0; i < itemsarray.length(); i++) {
ch_list = new ArrayList<Subitem_base_child>();
JSONObject itemsobj = itemsarray.getJSONObject(i);
Subitem_base subitem = new Subitem_base();
subitem.setGroupitemname(itemsobj.getString("BaseName"));
JSONArray subitemsarray=itemsobj.getJSONArray("subitems");
for (int j = 0; j <subitemsarray.length() ; j++) {
JSONObject subitemsobj=subitemsarray.getJSONObject(j);
Subitem_base_child subitembase=new Subitem_base_child();
subitembase.setChilditemname(subitemsobj.getString("SubItemdesc"));
String pricevalue = "£";
subitembase.setChilditemprice(pricevalue.concat(subitemsobj.getString("SubItemprice")));
ch_list.add(subitembase);
}
ch_lists.put(i, ch_list);
subitem.setItems(ch_lists.get(i));
list.add(subitem);
}
SubItem_ExpandAdapter subexpand = new SubItem_ExpandAdapter(getApplicationContext(), list,SubMenu.this);
int childCount=sec.getChildCount();
Log.d("Std", String.valueOf(childCount));
sec.setAdapter(subexpand);
subexpand.notifyDataSetChanged();
progressDialog.hide();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("SecondleveError", String.valueOf(error));
}
});
arrayRequest.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(arrayRequest);
}
}
MenuAdapter.java
public class SubItem_ExpandAdapter extends BaseExpandableListAdapter {
Context subcontext;
private ArrayList<Subitem_base> subitem_bases;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
String itembasename, itemde, subtmsub, subitempri;
private Activity parentActivity;
public SubItem_ExpandAdapter(Context subcontext, ArrayList<Subitem_base> subitem_bases, Activity parentactivity) {
this.subcontext = subcontext;
this.subitem_bases = subitem_bases;
this.parentActivity=parentactivity;
}
static class Groupname {
private TextView group_name;
private TextView groupitem_price;
private Button grouporder;
private ImageView droparrow;
}
static class Childnames {
private TextView item_name;
private TextView item_price;
private Button order;
}
#Override
public int getGroupCount() {
return subitem_bases.size();
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Subitem_base_child> subitem_base_children = subitem_bases.get(groupPosition).getItems();
return subitem_base_children.size();
}
#Override
public Object getGroup(int groupPosition) {
return subitem_bases.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Subitem_base_child> subitem_base_children = subitem_bases.get(groupPosition).getItems();
return subitem_base_children.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
Groupname groupname;
if (convertView == null) {
convertView = LayoutInflater.from(subcontext).inflate(R.layout.group_item, parent, false);
groupname = new Groupname();
groupname.group_name = (TextView) convertView.findViewById(R.id.group_name);
groupname.groupitem_price = (TextView) convertView.findViewById(R.id.groupitem_price);
groupname.grouporder = (Button) convertView.findViewById(R.id.grouporder);
groupname.droparrow = (ImageView) convertView.findViewById(R.id.droparrow);
convertView.setTag(groupname);
} else {
groupname = (Groupname) convertView.getTag();
}
Subitem_base groupitem = subitem_bases.get(groupPosition);
groupname.group_name.setText(groupitem.getGroupitemname());
if (isExpanded){
String[] elements = {groupitem.getGroupitemname() };
for (String s: elements) {
itembasename=s;
}
}
if (getChildrenCount(groupPosition)>=2) {
Log.d("Std", "called");
}else {
groupname.groupitem_price.setVisibility(View.VISIBLE);
groupname.droparrow.setVisibility(View.GONE);
groupname.grouporder.setVisibility(View.VISIBLE);
}
return convertView;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final Childnames childname;
if (convertView == null) {
convertView = LayoutInflater.from(subcontext).inflate(R.layout.child_item, parent, false);
childname = new Childnames();
childname.item_name = (TextView) convertView.findViewById(R.id.item_name);
childname.item_price = (TextView) convertView.findViewById(R.id.item_price);
childname.order = (Button) convertView.findViewById(R.id.order);
convertView.setTag(childname);
}else {
childname= (Childnames) convertView.getTag();
}
Subitem_base_child childitem = (Subitem_base_child) getChild(groupPosition, childPosition);
if (childitem.getChilditemname().isEmpty()){
childname.item_name.setVisibility(View.GONE);
}else {
childname.item_name.setText(childitem.getChilditemname());
}
childname.item_price.setText(childitem.getChilditemprice());
loginPreferences = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
final String status = loginPreferences.getString("Status", "");
if (status.equals("0")) {
childname.order.setBackgroundResource(R.drawable.cart_disable);
}else {
childname.order.setBackgroundResource(R.drawable.cart_button);
}
childname.order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (status.equals("0")) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(parentActivity);
SharedPreferences customerid = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String opentimes = customerid.getString("open", "");
alertDialogBuilder.setMessage(opentimes);
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
alertDialogBuilder.setCancelable(true);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
String poundre = childname.item_price.getText().toString();
subtmsub=childname.item_name.getText().toString();
subitempri = poundre.replace("£", "");
addcart();
}
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
private void addcart(){
loginPreferences = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
SharedPreferences customerid = subcontext.getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
loginPreferences.edit();
String customid = customerid.getString("customerid", "");
String cartdetails = itembasename + " " + subtmsub;
String cartspacong = cartdetails.replace(" ", "$");
cartspacong = cartspacong.replace("&", "and");
String addcarturl = Constant.commonurltake + "cart_process.php?userid=" + customid + "&Item=" + cartspacong + "&Itemcount=1&price=" + subitempri + "&page=items";
Log.d("Cart", addcarturl);
JsonArrayRequest cartreq = new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject cartobj = response.getJSONObject(i);
String cartnumber = cartobj.getString("count");
loginPrefsEditor.putString("Count", cartnumber);
BaseActivity.cartnumber.setVisibility(View.VISIBLE);
BaseActivity.cartnumber.setText(cartnumber);
loginPrefsEditor.apply();
if (cartobj.has("message")) {
Toast carttost = Toast.makeText(subcontext, cartobj.getString("message"), Toast.LENGTH_SHORT);
carttost.setGravity(Gravity.CENTER, 0, 0);
carttost.show();
} else {
Toast carttost = Toast.makeText(subcontext, "Product Added To Cart", Toast.LENGTH_SHORT);
carttost.setGravity(Gravity.CENTER, 0, 0);
carttost.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(subcontext, "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
}
I have a list view that implement swipelistadapter and app controller. The list view display correctly from the database, the only thing I need is to get position of each item and assign intent activity on each. These are my codes
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
Below Class is the main activity
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.158.33.172/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) v.findViewById(R.id.list);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//String selectedFromList = (listView.getItemAtPosition(position).getString());
// String text = movieList[position];
Intent i = new Intent(getActivity(), Tab2.class);
// i.putExtra("TEXT", text);
startActivity(i);
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
Any help will be appreciated. Thanks.
Code for getting a single item:
String singleItem = getItem(position);
this is quite straight forward. here is a modification to your onItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = movieList.get(position);
Intent i = new Intent(getActivity(), Tab2.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
just note that movieList object should be the same object you pass to your adapter
i am new to the concept of the fragments i am using the tab layout where one of the tab consists of the list view in that i had used the base adapter to describe the list row where i want to refresh the second tab when button from the first tab is clicked.i had tried the fragment transaction method but its not doing the work that i want please help here
this is the baseadapter
public class Second_adapter extends BaseAdapter {
Context context;
Activity activity;
TextView basename, SubItemprice, itemdesc, SubItemdesc;
LayoutInflater inflater;
ImageView order;
private List<JSONParser> items;
String itembasename, itemde, subtmsub, subitempri;
SharedPreferences.Editor loginPrefsEditor;
public Second_adapter(Context context, List<JSONParser> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.item_clicked, viewGroup, false);
basename = (TextView) view.findViewById(R.id.basename);
SubItemprice = (TextView) view.findViewById(R.id.SubItemprice);
itemdesc = (TextView) view.findViewById(R.id.itemdesc);
SubItemdesc = (TextView) view.findViewById(R.id.SubItemdesc);
order = (ImageView) view.findViewById(R.id.order);
final JSONParser setdata = items.get(i);
basename.setText(setdata.getBaseName());
itemdesc.setText(setdata.getItemdesc());
SubItemdesc.setText(setdata.getSubItemdesc());
SubItemprice.setText(setdata.getSubItemprice());
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itembasename = setdata.getBaseName();
itemde = setdata.getItemdesc();
subtmsub = setdata.getSubItemdesc();
subitempri = setdata.getSubItemprice();
Session userloggedin = new Session(context);
if (userloggedin.isLoggedIn()) {
addcart();
Cart cart = new Cart();
FragmentManager fragmentManager = activity.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.cartfragment, cart);
Toast.makeText(context, "LoggedIn"+ itembasename+itemde+subtmsub+subitempri, Toast.LENGTH_SHORT).show( );
}else{
Toast.makeText(context,"Please Login", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void addcart() {
SharedPreferences customerid=context.getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String addcarturl = "http://standardtakeaway.co.uk/json/cart_ p rocess.p h p?userid = "+customid+" & Item=" + itembasename+itemde+subtmsub+" & Itemcount=1&price="+subitempri;
Log.d("Cart",addcarturl);
JsonArrayRequest cartreq=new JsonArrayRequest(Request.Method.POST, addcarturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i=0; i<response.length();i++){
try {
JSONObject cartobj=response.getJSONObject(i);
// String count=cartobj.getString("count");
// loginPrefsEditor.putString("Badge",count);
// loginPrefsEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,""+error, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(cartreq);
}
}
This is the Another tab where i want it to refresh
public class Cart extends Fragment {
Button check_out;
TextView subtotal;
ListView cartview;
CartAdapter cartAdapter;
List<JSONParser> cartitems;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View cartfrag = inflater.inflate(R.layout.cart, container, false);
subtotal = (TextView) cartfrag.findViewById(R.id.subtotal);
cartview = (ListView) cartfrag.findViewById(R.id.cartview);
cartitems = new ArrayList<JSONParser>();
cartAdapter = new CartAdapter(getActivity(), cartitems);
cartview.setAdapter(cartAdapter);
check_out = (Button) cartfrag.findViewById(R.id.check_out);
check_out.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart_check = new Intent(getActivity(), Check.class);
startActivity(cart_check);
}
});
cartdata();
return cartfrag;
}
void cartdata() {
SharedPreferences customerid=getActivity().getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
String customid=customerid.getString("customerid","");
String carturl = "http://standardtakeaway.co.uk/json/view_cart.php?userid=" + customid;
Log.d("CartData", carturl);
JsonObjectRequest cartreq = new JsonObjectRequest(Request.Method.GET, carturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray objarray = response.getJSONArray("items");
for (int i = 0; i < objarray.length(); i++) {
JSONObject cartdataobj = objarray.getJSONObject(i);
JSONParser parserdata = new JSONParser();
parserdata.setCartquantity(cartdataobj.getString("qty"));
parserdata.setCartbase(cartdataobj.getString("BaseName"));
parserdata.setCartprice(cartdataobj.getString("price"));
cartitems.add(parserdata);
}
JSONObject subobj=response.getJSONObject("details");
String subtext=subobj.getString("subtotal");
subtotal.setText(subtext);
} catch (JSONException e) {
e.printStackTrace();
}
cartAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
});
cartreq.setRetryPolicy(new DefaultRetryPolicy(6000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(cartreq);
}
public static Cart getInstance(String message) {
Cart cart = new Cart();
Bundle bundle = new Bundle();
bundle.putString("MSG", message);
cart.setArguments(bundle);
return cart;
}
}