I cannot select an item in the android listview. I've already set:
android:choiceMode="singleChoice"
android:listSelector="#drawable/gratis_selector"
this worked fine on other layouts where i had only the listview in the fragment. I tired to print out the position of the click but it seems like the click is not recognized.
Here is my layout:
<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"
tools:context="com.cosicervin.administration.fragments.ChangePriceFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.13"
android:text="PLZ/Ort" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.13"
android:text="Limousine Preis" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.13"
android:text="Kombi Preis" />
<TextView
android:id="#+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.13"
android:text="Bus Preis" />
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.13" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Neu"
android:id="#+id/new_place_button"/>
</LinearLayout>
<LinearLayout
android:id="#+id/price_swipe_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/places_listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:listSelector="#drawable/gratis_selector"
/>
</LinearLayout>
I've made my own adapter but this is not the problem i think, here is the fragment code as well :
public class ChangePriceFragment extends Fragment implements GeneralFragment{
ListView placesListView;
String serverRequestToken;
String serverUrl;
View view;
ArrayList<Place> places;
PlaceListAdapter adapter;
RequestQueue requestQueue;
Place selectedPlace;
SwipeRefreshLayout swipe;
Button newPlacebButton;
public ChangePriceFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_change_price, container, false);
serverUrl = ((MainActivity)getActivity()).server_url;
serverRequestToken = ((MainActivity)getActivity()).server_request_token;
requestQueue = MyRequestQueue.getInstance(getContext()).getRequestQueue();
placesListView = (ListView) view.findViewById(R.id.places_listView);
placesListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.e("Position", Integer.toString(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
placesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("Position", Integer.toString(position));
}
});
newPlacebButton = (Button) view.findViewById(R.id.new_place_button);
newPlacebButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NewPlaceFragment newPlaceFragment = new NewPlaceFragment();
newPlaceFragment.show(getFragmentManager(),"New Place");
}
});
places = new ArrayList<>();
adapter = new PlaceListAdapter(getActivity().getApplicationContext(), R.layout.places_list_layout, null);
placesListView.setAdapter(adapter);
placesListView.setSelection(R.drawable.gratis_selector);
fetchPlacesFromServer();
return view;
}
private void fetchPlacesFromServer(){
final Map<String, String> params = new HashMap<>();
params.put("token", serverRequestToken);
params.put("service","15");
final String URL = serverUrl + "/administration_services.php";
CustomRequest customRequest = new CustomRequest(Request.Method.POST, URL, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
adapter.deleteAll();
adapter.notifyDataSetChanged();
try {
JSONArray array = response.getJSONArray("places");
for(int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
Place place = new Place();
place.setId(object.getInt("id"));
place.setName(object.getString("place_name"));
place.setCarPrice(object.getInt("car_price"));
place.setVanPrice(object.getInt("van_price"));
place.setBusPrice(object.getInt("bus_price"));
places.add(place);
adapter.add(place);
adapter.notifyDataSetChanged();
Log.i("Place", place.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(customRequest);
}
private void changePlacePrices(){
Map<String, String> params = new HashMap<>();
params.put("token", serverRequestToken);
params.put("service", "16");
params.put("place_id",Integer.toString(selectedPlace.getId()));
params.put("place_name", selectedPlace.getName());
params.put("car_price", Integer.toString(selectedPlace.getCarPrice()));
params.put("van_price", Integer.toString(selectedPlace.getVanPrice()));
params.put("bus_price", Integer.toString(selectedPlace.getBusPrice()));
final String URL = serverUrl + "/administration_services.php";
CustomRequest customRequest = new CustomRequest(Request.Method.POST, URL, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
int code = 1;
try {
code = response.getInt("code");
} catch (JSONException e) {
e.printStackTrace();
}
if(code == 2){
Toast.makeText(getContext(), "Gespeichert", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(customRequest);
}
}
I found what the problem was i mean it still is in a way. I've added to the custom listview row in the xml the line :
android:descendantFocusability="blocksDescendants"
and now when I click on the space between the items in the list is focusable but when i click on a value in the listview it wont work. I would be awesome if someone knew hot to solve this new problem.
Related
I want to display ("Empty") at RecyclerView when there are no data available at a table. Now, my currentview when no data is avaialble will like as image below
https://scontent.fkul14-1.fna.fbcdn.net/v/t1.0-9/60093724_10216107031681720_3339793009188274176_n.jpg?_nc_cat=106&_nc_eui2=AeE2gJxeFI5ifgJkgcAXJZbsvtp3BiL6w5TtndQ4PO5emnLkh93oOJ_37m6KjbsZJ0QZsU8T6a9q_0Bg38t80eJcwkSiPbye1y9Ad6Ssx2TUrA&_nc_ht=scontent.fkul14-1.fna&oh=2a7d7090bfa7945893bcb973fc26005b&oe=5D5CE2D8
The name "Tan Kian Guan" stay available maybe due to if the user is login, it will get all information about user in table "users".
Below is my code.
MyHistoryList.java
public class MyHistoryList extends AppCompatActivity {
List<User> userList;
RecyclerView recyclerView;
private String approveID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_history_list);
if(getIntent() != null) {
approveID = getIntent().getStringExtra("approveType");
}
else{}
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_my_history_list, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("MY HISTORY LIST");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
// abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
recyclerView = findViewById(R.id.recylcerView);
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.VERTICAL));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
User user = SharedPrefManager.getInstance(this).getUser();
userList = new ArrayList<>();
loadHistory(user.getBadgeid());
}
private void loadHistory(String badgeid) {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URLs.URL_LIST+"?badgeid="+ badgeid,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject userJson = array.getJSONObject(i);
userList.add(new User(
userJson.getInt("id"),
userJson.getString("name"),
userJson.getString("badgeid"),
userJson.getString("position"),
userJson.getString("department"),
userJson.getString("factory"),
userJson.getString("reviewer"),
userJson.getString("title"),
userJson.getString("year"),
userJson.getString("month"),
userJson.getString("suggestionwill"),
userJson.getString("present"),
userJson.getString("details"),
userJson.getString("benefit"),
userJson.getString("photo"),
userJson.getString("status"),
userJson.getString("comment")
));
}
UserAdapter adapter = new UserAdapter(MyHistoryList.this, userList);
recyclerView.setAdapter(adapter);
adapter.setClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int post = recyclerView.indexOfChild(v);
User user = userList.get(post);
Intent myIntent = new Intent(MyHistoryList.this, MyHistory.class);
myIntent.putExtra("user", user);
myIntent.putExtra("approveType",approveID);
startActivity(myIntent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
}
activity_my_history_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/haha"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MyHistoryList">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:maxLines="1"
android:clickable="false"
android:focusable="false"
android:longClickable="false"
android:textStyle="bold"
android:textSize="18sp"
android:textColor="#FFFFFF" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Can anyone help? Thanks
You can know the empty data while you parse the data,
Try this,
Edit:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/haha"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MyHistoryList">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:maxLines="1"
android:clickable="false"
android:focusable="false"
android:longClickable="false"
android:textStyle="bold"
android:textSize="18sp"
android:textColor="#FFFFFF" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recylcerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/emptyView"
android:text="List is Empty"
android:textSize="#dimen/text_15sp"/>
</LinearLayout>
Declare textview id in the Activity:
public class MyHistoryList extends AppCompatActivity {
List<User> userList;
TextView emptyView;
RecyclerView recyclerView;
private String approveID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_history_list);
//Declare TextView
emptyView = findiViewById(R.id.emptyView);
if(getIntent() != null) {
approveID = getIntent().getStringExtra("approveType");
}
private void loadHistory(String badgeid) {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URLs.URL_LIST+"?badgeid="+ badgeid,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
//add this condition
if(array.length() == 0){
//display empty with your code.
emptyView.setVisibility(View.VISIBLE);
recylcerView.setVisibility(View.GONE);
}else{
emptyView.setVisibility(View.GONE);
recylcerView.setVisibility(View.VISIBLE);
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject userJson = array.getJSONObject(i);
userList.add(new User(
userJson.getInt("id"),
userJson.getString("name"),
userJson.getString("badgeid"),
userJson.getString("position"),
userJson.getString("department"),
userJson.getString("factory"),
userJson.getString("reviewer"),
userJson.getString("title"),
userJson.getString("year"),
userJson.getString("month"),
userJson.getString("suggestionwill"),
userJson.getString("present"),
userJson.getString("details"),
userJson.getString("benefit"),
userJson.getString("photo"),
userJson.getString("status"),
userJson.getString("comment")
));
}
}
UserAdapter adapter = new UserAdapter(MyHistoryList.this, userList);
recyclerView.setAdapter(adapter);
adapter.setClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int post = recyclerView.indexOfChild(v);
User user = userList.get(post);
Intent myIntent = new Intent(MyHistoryList.this, MyHistory.class);
myIntent.putExtra("user", user);
myIntent.putExtra("approveType",approveID);
startActivity(myIntent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
This works. Try and let me know. Happy coding.
try like this
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<TextView
android:id="#+id/empty_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="#string/no_data_available" />
in your class file
#Override
public void onResponse(String response) {
if(response==null){
recyclerView.setVisibility(View.Gone)
emptyView.setVisibility(View.Visible)
}else{
try {
JSONArray array = new JSONArray(response);
//add this condition
if(array.length() == 0){
I am wanting to display orders on a screen which I retrieve from a database. Each order has various items on it, and the screen will show the details of various orders and their items.
For example:
Order 1
Item1
Item2
Item3
Order2
Item4
Item5
,etc.
I am able to return this data with no issues, however I was wondering how to put a border around each order (as opposed to each item which is easy to do).
This is what the return looks like now (apologies as it does not show everything I wanted in this image). Basically I want a border around each specific order, so all the items in order 1 I want in a border, and then all the items in order 2 I want in a border.
The code is outline below and any help would be greatly appreciated:
This is the activity which displays the orders:
public class ChefScreen extends AppCompatActivity {
ListView listView;
List<ChefOrderList> listOrders;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chef_screen);
listView = findViewById(R.id.list_chef_orders);
listOrders = new ArrayList<>();
displayOrders();
}
private void displayOrders(){
String url = "hidden";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("orders");
for (int i = 0; i < array.length(); i++) {
final JSONObject orderObj = array.getJSONObject(i);
ChefOrderList c = new ChefOrderList(orderObj.getString("menu_item_name"), orderObj.getString("item_type"), orderObj.getString("order_date_time"),
orderObj.getInt("quantity_ordered"), orderObj.getInt("order_id"));
listOrders.add(c);
}
ChefOrderAdapter adapter = new ChefOrderAdapter(listOrders, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ChefScreen.this, "Oops! " +error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("menuid", "0");
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
This is the layout for the chef screen:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChefScreen">
<ListView
android:id="#+id/list_chef_orders"
android:layout_width="330dp"
android:layout_height="430dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="15dp"
android:layout_marginTop="81dp"
tools:layout_editor_absoluteX="20dp"
tools:layout_editor_absoluteY="77dp" />
</RelativeLayout>
The adapter:
public class ChefOrderAdapter extends ArrayAdapter<ChefOrderList> {
private List<ChefOrderList> chefOrderList1;
private Context context;
public ChefOrderAdapter(List<ChefOrderList> M, Context C){
super(C, R.layout.listcheforders, M);
this.chefOrderList1 = M;
this.context = C;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.listcheforders,null,true);
TextView orderNumber = view.findViewById(R.id.tvOrderNumber);
TextView itemType = view.findViewById(R.id.tvItemType);
TextView itemName = view.findViewById(R.id.tvItemName);
TextView orderQuantity = view.findViewById(R.id.tvItemQty);
TextView orderTime = view.findViewById(R.id.tvDateTime);
ChefOrderList chefOrderList = chefOrderList1.get(position);
itemName.setText(chefOrderList.getName());
orderQuantity.setText("Qty: " +chefOrderList.getQty());
if(position>0){
ChefOrderList prevChefOrderList = chefOrderList1.get(position-1);
if(chefOrderList.getOrder() != (prevChefOrderList.getOrder())){
orderNumber.setText("Order: " +chefOrderList.getOrder());
orderTime.setText(chefOrderList.getDate());
}
if(!chefOrderList.getType().equals(prevChefOrderList.getType())){
itemType.setText(chefOrderList.getType());
}
} else {
itemType.setText(chefOrderList.getType());
orderNumber.setText("Order: " +chefOrderList.getOrder());
orderTime.setText(chefOrderList.getDate());
}
return view;
}
}
The model class:
public ChefOrderList(String name, String type, String date, int qty, int order) {
Name = name;
Type = type;
Date = date;
Qty = qty;
Order = order;
}
public String getDate() {
return Date;
}
public String getName() {
return Name;
}
public String getType() {
return Type;
}
public int getQty() {
return Qty;
}
public int getOrder() {
return Order;
}
}
and finally the layout file for the list or orders:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<TextView
android:id="#+id/tvOrderNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/tvItemName"
android:layout_marginTop="59dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000"
android:textSize="30sp" />
<TextView
android:id="#+id/tvDateTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/tvItemName"
android:layout_marginTop="15dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000" />
<TextView
android:id="#+id/tvItemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="20dp"
android:layout_marginTop="166dp"
android:text="placeholderName"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000" />
<TextView
android:id="#+id/tvItemQty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/tvItemName"
android:layout_marginTop="216dp"
android:text="qty"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000" />
<TextView
android:id="#+id/tvItemType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tvItemName"
android:layout_alignStart="#+id/tvItemName"
android:layout_marginBottom="-166dp"
android:paddingBottom="20dp"
android:text=""
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#000"
android:textSize="26sp"
android:textStyle="italic"
tools:text="text" />
</RelativeLayout>
Sorry for my english, not my first language.
Im creating an app in Android and I have a issue:
I have a TabBar with 2 fragments (1 - ProductFragment and 2 - CartFragment), in second Fragment (CartFragment) I have a ListView and that ListView is initial null.
CartFragment Layout:
<FrameLayout 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:padding="15dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lancarvenda_carrinho_lvwresultado"
android:orientation="vertical" />
</LinearLayout>
</FrameLayout>
In ProductFragment I have a button with onclick, that onclick Intents another activity and in that activity I add values in my public Custom List:
public static List<PesquisarProdutoResponse> Carrinho = new ArrayList<>();
When I done with adding values that I need, I close that activity and return to TabBar and expects that ListView has been populated.
The method that populate my public list:
private void PesquisarProduto()
{
RequestQueue sQueue = Volley.newRequestQueue(getActivity());
String sEnderecoBase = "http://www.my-url";
StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
if (sResultado.getCodigoRetorno() != 0)
{
//lastText = "Produto não encontrado";
//barcodeView.setStatusText("Produto não encontrado");
}
else
{
Variaveis.Carrinho.add(sResultado);
try {
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar = new ArrayList<>();
for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
sCarrinhoAuxiliar.add(sItem);
}
LancarVendaCarrinhoListViewAdapter sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(),
sCarrinhoAuxiliar);
fCarrinhoResultado.setAdapter(sAdaptador);
sAdaptador.notifyDataSetChanged();
Object oi = fCarrinhoResultado.getCount();
oi.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
byte[] sBytesResposta = error.networkResponse.data;
String sTexto = new String(sBytesResposta);
Mensagem.ExibirAlert(getActivity(), String.valueOf(error.networkResponse.statusCode));
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> sHeaders = new HashMap<>();
sHeaders.put("Authorization", "Bearer " + Variaveis.ApiToken);
return sHeaders;
}
#Override
public byte[] getBody() throws AuthFailureError
{
return new Gson().toJson(sCorpoBusca).getBytes();
}
#Override
public String getBodyContentType()
{
return "application/json";
}
};
sQueue.add(sRequest);
}
ListView Adapter:
public class LancarVendaCarrinhoListViewAdapter extends BaseAdapter
{
private Context mContext;
//private LayoutInflater mInflater;
private List<PesquisarProdutoObjetoRetorno> mDataSource;
public LancarVendaCarrinhoListViewAdapter(Context context, List<PesquisarProdutoObjetoRetorno> items)
{
mContext = context;
mDataSource = items;
}
#Override
public int getCount() {
return mDataSource.size();
}
#Override
public Object getItem(int position) {
return mDataSource.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
try
{
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View sView = mInflater.inflate(R.layout.activity_lancarvenda_carrinho_list_view_item, parent, false);
PesquisarProdutoObjetoRetorno sItem = (PesquisarProdutoObjetoRetorno) getItem(position);
TextView descricao = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txtdescricao);
descricao.setText(sItem.getDescricao());
TextView preco = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txvpreco);
preco.setText(String.valueOf(sItem.getPreco()));
EditText quantidade = (EditText)sView.findViewById(R.id.lancarvenda_carrinho_item_etquantidade);
quantidade.setText("1");
return sView;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
My layout of row:
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/lancarvenda_carrinho_item_imvFoto"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center_horizontal"
android:background="#drawable/circulo_foto2"
app:border_color="#898989"
app:border_width="2dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="10dp">
<TextView
android:id="#+id/lancarvenda_carrinho_item_txtdescricao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Relogio"
android:textSize="20dp"
android:textStyle="bold"
android:layout_marginRight="8dp"
android:lines="2"
android:minLines="2"
android:singleLine="false"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/lancarvenda_carrinho_item_txvpreco"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="R$ 399,89"
android:textColor="#1ba39c"
android:textSize="20dp"
android:layout_marginRight="70dp"/>
<EditText
android:id="#+id/lancarvenda_carrinho_item_etquantidade"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:backgroundTint="#9a9b9c"
android:hint="0"
android:textColor="#2a2d2e"
android:layout_marginRight="8dp"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
In debug mode, when code pass in getCount in Adapter, I have size more than 1 and my list still not show! Even if I close TabBar and reopen and set adapter (with values) on onCreate method.
What can I do to my ListView show?
EDIT
I inflate listview on onCreate:
super.onCreate(savedInstanceState);
LayoutInflater sInflater = getActivity().getLayoutInflater();
View sView = sInflater.inflate(R.layout.fragment_lancarvenda_carrinho, null);
fCarrinhoResultado = (ListView) sView.findViewById(R.id.lancarvenda_carrinho_lvwresultado);
Try making your list a member of the class instead of a local variable
private void PesquisarProduto()
{
RequestQueue sQueue = Volley.newRequestQueue(getActivity());
String sEnderecoBase = "http://www.my-url";
StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
// Make cart list a private data member so it doesn't loose scope //
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
#Override
public void onResponse(String response)
{
PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
if (sResultado.getCodigoRetorno() != 0)
{
//lastText = "Produto não encontrado";
//barcodeView.setStatusText("Produto não encontrado");
}
else
{
Variaveis.Carrinho.add(sResultado);
try {
sCarrinhoAuxiliar = new ArrayList<>();
...
}
...
}
...
}
...
}
...
}
Declare your List sCarrinhoAuxiliar and adapter sAdaptador as global.
Update your OnCreateView() as below:
// Global
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
LancarVendaCarrinhoListViewAdapter sAdaptador;
.........................
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
....................
........................
sCarrinhoAuxiliar = new ArrayList<>();
sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(), sCarrinhoAuxiliar);
fCarrinhoResultado.setAdapter(sAdaptador);
.......................
...............
}
Update your onResponse() method as below:
#Override
public void onResponse(String response) {
.....................
..........................
try {
// Clear old data
sCarrinhoAuxiliar.clear();
for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
sCarrinhoAuxiliar.add(sItem);
}
// Update list
sAdaptador.notifyDataSetChanged();
.............
....................
}
catch (Exception e) {
e.printStackTrace();
}
}
Hope this will help~
I got help from another forum and I was able to solve my problem:
I override two methods: OnCreate (inflate and receive view) and OnCreateView (find the product and put on listview), I eliminate method OnCreate and put everything on OnCreateView!
That solve my problem!
Thanks to everybody!
i want to load Mysql data into listview into fragment
which contain image and text view stored previously into mysql database
this is my code but it show me error in getLayoutInflater
how can i do this ?
public class NewsFragment extends Fragment {
RequestQueue requestQueue;
String url = "http://giclub.esy.es/show.php";
ListView listView;
View myView;
ArrayList<NewsList> Newslistitem = new ArrayList<NewsList>();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.newslayout,container,false);
listView = (ListView) myView.findViewById(R.id.listView);
requestQueue = Volley.newRequestQueue(this.getActivity());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("allstudents");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String info = respons.getString("info");
String img = respons.getString("img");
Newslistitem.add(new NewsList(id,name, info, img));
}
listAllItme();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
return myView;
}
public void listAllItme() {
listAdpter lA = new listAdpter(Newslistitem);
listView.setAdapter(lA);
}
/* public void onClick(View view) {
Intent intent = new Intent(this.getActivity(),NewsFragment.class);
startActivity(intent);
finish();
}*/
class listAdpter extends BaseAdapter {
ArrayList<NewsList> listA = new ArrayList<NewsList>();
public listAdpter(ArrayList<NewsList> listA) {
this.listA = listA;
}
#Override
public int getCount() {
return listA.size();
}
#Override
public Object getItem(int position) {
return listA.get(position).id;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.news_itm, null);
//TextView id = (TextView) view.findViewById(R.id.textView_id);
TextView name = (TextView) view.findViewById(R.id.textaddress);
TextView info = (TextView) view.findViewById(R.id.text_info);
ImageView img = (ImageView) view.findViewById(R.id.newspic);
// id.setText(listA.get(position).id);
name.setText(listA.get(position).name);
info.setText(listA.get(position).info);
Picasso.with(NewsFragment.this.getActivity()).load("http://giclub.esy.es/image/" + listA.get(position).img).into(img);
return view;
}
}
}
NewsList.java
public class NewsList {
public String id;
public String name;
public String info;
public String img;
public NewsList(String id ,String name, String info, String img) {
this.id = id;
this.name = name;
this.info = info;
this.img = img;
}
}
news_itm.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="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/newspic"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="اقرأ المزيد"
android:textAlignment="center"
android:id="#+id/text_info"
android:layout_gravity="center"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_marginStart="35dp" />
<TextView
android:text="TextView"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginTop="27dp"
android:textSize="15dp"
android:id="#+id/textaddress"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</LinearLayout>
how can i do that ?
first of all i will recommend to split the code between the ui and the data access, then load the data in a different threat and not in the ui thread
try loading the screen first with a dummy data to check that the layout and the screen works properly then connect it to the "DAL" with your saved data
Your are inflating the newslayout While Your layout is **news_itm.xml**
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView inflater.inflate(R.layout.**newslayout**,container,false);
As the title says, my ListFragment doesn't show items retrieved from firebase, here my code:
CONTAINER:
public class MainPageLogin extends AppCompatActivity {
private BottomBar mBottomBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page_login);
// mBottomBar = BottomBar.attach(this, savedInstanceState);
mBottomBar = BottomBar.attachShy((CoordinatorLayout) findViewById(R.id.myCoordinator),
findViewById(R.id.myScrollingContent), savedInstanceState);
mBottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
new BottomBarFragment(ChatListFragment.newInstance(R.layout.chat_list_fragment,0), R.drawable.ic_action_user, "Chat"),
new BottomBarFragment(PollListFragment.newInstance(R.layout.poll_list_fragment,1), R.drawable.ic_assessment, "Sondaggi"),
new BottomBarFragment(ContactListFragment.newInstance(R.layout.contact_list_fragment,2), R.drawable.ic_contacts, "Contatti")
);
mBottomBar.setActiveTabColor("#C83F09");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Necessary to restore the BottomBar's state, otherwise we would
// lose the current tab on orientation change.
mBottomBar.onSaveInstanceState(outState);
}}
CONTAINER XML
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myCoordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v4.widget.NestedScrollView
android:id="#+id/myScrollingContent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="200dp"></FrameLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
LISTFRAGMENT JAVA
public class ChatListFragment extends ListFragment {
ListView usr_chats;
Button btn_crea;
StringBuilder total;
TextView nochat;
RequestQueue queue;
TextView chat_item;
FirebaseListAdapter<String> Fireadapter;
View v;
public ChatListFragment(){}
public static ChatListFragment newInstance(int res, int i){
ChatListFragment f = new ChatListFragment();
Bundle args = new Bundle();
args.putInt("res", res);
args.putInt("choice",i);
f.setArguments(args);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.chat_list_fragment, container, false);
nochat = (TextView) v.findViewById(R.id.no_chat);
btn_crea = (Button) v.findViewById(R.id.crea_chat);
usr_chats = (ListView) v.findViewById(android.R.id.list);
//-------------------------------
return v;
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
total = new StringBuilder();
total.append("");
btn_crea.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(),contacts.class);
intent.putExtra("KEY",total.toString());
startActivity(intent);
}
});
Firebase.setAndroidContext(getContext());
try {
FileInputStream inputStream = getActivity().openFileInput("usr_basekey");
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
//Log.d("VOTA",total.toString());
} catch (FileNotFoundException e) {
Log.d("VOTA", "FILE NON TROVATO:" + e.getMessage());
} catch (IOException e) {
Log.d("VOTA", "IO EXCEPTION:" + e.getMessage());
}
Firebase myFirebaseRef = new Firebase("https://fiery-fire-7347.firebaseio.com/user/"+total.toString());
myFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
String user_params = snapshot.getValue().toString();
try {
JSONObject jsonO = new JSONObject(user_params);
String user_name = jsonO.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(FirebaseError error) {
}
});
Firebase chats = myFirebaseRef.child("chatadded");
queue = Volley.newRequestQueue(getContext());
Log.d("VOTA","preListAdapter");
Fireadapter = new FirebaseListAdapter<String>(
getActivity(),
String.class,
R.layout.chat_user_list,
chats
) {
#Override
protected void populateView(View view, final String s, int i) {
chat_item = (TextView) view.findViewById(R.id.chat_name_for_users);
String url = "https://fiery-fire-7347.firebaseio.com/chats/"+s+"/nomeChat.json";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("VOTA","ResponseAdapter-"+response);
chat_item.setText(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("VOTA", "Volley Error: " + error);
}
});
queue.add(stringRequest);
}
};
usr_chats.setAdapter(Fireadapter);
Log.d("VOTA", "postListAdapter");
usr_chats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), ChatActivityHome.class);
intent.putExtra("nChat","");
intent.putExtra("myKey",total.toString());
intent.putExtra("kChat", Fireadapter.getItem(position));
startActivity(intent);
}
});
//-----------------------------
}}
LISTVIEW XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.gitlab.votateam.votateam.MainPage">
<ListView
android:id="#+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/crea_chat"
android:layout_alignParentTop="true" />
<TextView
android:textColor="#737373"
android:id="#+id/no_chat"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/android:list"
android:layout_centerHorizontal="true"
android:layout_marginTop="102dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Crea Chat"
android:id="#+id/crea_chat"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
ITEMS XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/imageView"
android:src="#drawable/def_groupchat_profile"
/>
<TextView
android:textColor="#737373"
android:text=""
android:id="#+id/chat_name_for_users"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageView"
android:layout_toEndOf="#+id/imageView"
android:layout_marginLeft="14dp"
android:layout_marginStart="14dp"
android:layout_marginTop="12dp" />
</RelativeLayout>
I'm sure the code works, and the error should be related to XML because my log shows the correct "response" from the firebase DB.
You're firing an async request to get a string StringRequest. By the time that string comes back, Android is not expecting changes to the view anymore and it doesn't update the view.
The solution is typically to call notifyDataSetChanged():
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("VOTA","ResponseAdapter-"+response);
chat_item.setText(response);
}
}, ...