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);
}
}, ...
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 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.
i've had a problem, when i've tried to view this below fragment showing "skipping layout". Can any one help me out how to solve this problem please.
I'm getting this "No adapter attached; skipping layout." when i CLICK any imageview on ThirdFragment UI ayout, not when the images display in Thirdfragment UI layout.
ThirdFrament.java
public class ThirdFragment extends Fragment implements RecyclerViewAdapter.ItemListener {
static final String url = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesData.txt" ;
RecyclerView recyclerView;
RecyclerViewAdapter adapter;
AutoFitGridLayoutManager layoutManager;
private static List<JsonURLFullModel> cart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
new JSONTask().execute(url, this);
// Inflate the layout for this fragment
return rootView;
}
public class JSONTask extends AsyncTask<Object, String, ThirdFragModel> {
// Url , , return_value_of_doInBackground
//private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//dialog.show(); // this is for ProgressDialog
}
#Override
protected ThirdFragModel doInBackground(Object... params) {
//send and receive data over the web
// can be used to send and receive "streaming" data whose length is not
// known in advance
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0].toString());
RecyclerViewAdapter.ItemListener itemListener = (RecyclerViewAdapter.ItemListener) params[1];
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream(); // this is used to store
// the response, response is always stream
reader = new BufferedReader(new InputStreamReader(stream));
// BufferedReader reads the stream line by line and then store in the reader
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString(); // this contails whole JSON data from the URL
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies"); // "movies" is the JSON Array-object in JSON data URL
List<JsonURLFullModel> movieModelList = new ArrayList<>();
//StringBuffer finalBufferedaData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i); // getting first json object from JSON ARRAY "movies"
JsonURLFullModel movieModel = new JsonURLFullModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setImage(finalObject.getString("image"));
movieModelList.add(movieModel); // adding the final object in list
//finalBufferedaData.append(movieName +"-"+ year +"\n");
}
ThirdFragModel thirdFragModel= new ThirdFragModel(itemListener,movieModelList);
return thirdFragModel;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
adapter = new RecyclerViewAdapter(getActivity(), result.getMovieModelList(), result.getItemListener());
/**
AutoFitGridLayoutManager that auto fits the cells by the column width defined.
**/
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
/**
Simple GridLayoutManager that spans two columns
**/
/*GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(manager);*/
//AnimationUtils.animate(jsonFullL1, true);
}
}
public void moveToLoginActivity() {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
#Override
public void onItemClick(int mPosition,List<JsonURLFullModel> mValues ) {
Log.d("Fragposition",mPosition+":"+mValues);
Toast.makeText(getActivity(), mValues.get(mPosition).getMovie() + " is clicked", Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(getActivity(), FullScreenViewActivity.class);
Intent intent = new Intent(getActivity(), FullScreenViewInitialActivity.class);
intent.putExtra("position", mPosition);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
public static List<JsonURLFullModel> getCart() {
if(cart == null) {
cart = new Vector<JsonURLFullModel>();
}
return cart;
}
}
Here is my adapter class which we used in ThirdFragment class as shown above
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
static List<JsonURLFullModel> mValues;
Context mContext;
private ItemListener mListener;
static int mPosition;
public RecyclerViewAdapter(Context context, List<JsonURLFullModel> values, ItemListener itemListener) {
mValues = values;
mContext = context;
mListener=itemListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textView;
public ImageView imageView;
public RelativeLayout relativeLayout;
JsonURLFullModel item;
public ViewHolder(View v) {
super(v);
v.setOnClickListener(this);
textView = (TextView) v.findViewById(R.id.textView1);
imageView = (ImageView) v.findViewById(R.id.imageView1);
relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);
}
public void setData(final JsonURLFullModel item) {
this.item = item;
Log.d("INFO",item.getImage());
//https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit
Picasso.with(mContext)
.load(item.getImage())
.error(R.drawable.ferrari)
.noPlaceholder()
.noFade()
.fit()
.into(imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
//Success image already loaded into the view
Log.d("INFO","success");
}
#Override
public void onError() {
//Error placeholder image already loaded into the view, do further handling of this situation here
Log.d("INFO","error");
}
});
/*imageView.post(new Runnable() {
#Override
public void run(){
Glide.with(mContext).load(item.getImage()).asBitmap().override(1080, 600).into(imageView);
}
});*/
textView.setText(item.getMovie());
}
#Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClick(getAdapterPosition(),mValues); // this.getPosition() is depricated
// in API 22 and we got getAdapterPosition()
}
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder Vholder, int position) {
Vholder.setData(mValues.get(position));
mPosition=position;
}
#Override
public int getItemCount() {
return mValues.size();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
}
FullScreenViewInitialActivity.java
public class FullScreenViewInitialActivity extends FragmentActivity {
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
static ArrayList<JsonURLFullModel> mValues;
static int position;
Button addToBagButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view_initial);
addToBagButton = (Button) findViewById(R.id.b_add_to_bag);
Intent i = getIntent();
position=i.getIntExtra("position",0);
Log.d("Acposition",""+position);
mValues = (ArrayList<JsonURLFullModel>) getIntent().getSerializableExtra("values");
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.intial_pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
viewPager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
CircleIndicator circleIndicator = (CircleIndicator) findViewById(R.id.imageIndicator);
circleIndicator.setViewPager(viewPager);
/*viewPager.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewActivity.class);
intent.putExtra("position", position);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
});*/
final List<JsonURLFullModel> cart = ThirdFragment.getCart();
final JsonURLFullModel selectedProduct = mValues.get(position);
addToBagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cart.add(selectedProduct);
Log.d("cart",""+cart.size());
//finish();
Button b_add_to_bag = (Button) findViewById(R.id.b_add_to_bag);
b_add_to_bag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reviewOrderIntent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewReviewActivity.class);
startActivity(reviewOrderIntent);
}
});
}
});
if(cart.contains(selectedProduct)) {
addToBagButton.setEnabled(false);
addToBagButton.setText("Item in Cart");
}
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mValues.size();
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
/*Bundle bundle = getArguments();
int position = bundle.getInt("position");*/
//JsonURLFullModel imageFileName = mValues.get(position);
try {
BitmapFactory.Options options = new BitmapFactory.Options();
/*options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;*/
URL url = new URL(mValues.get(position).getImage());
Log.d("position",""+position);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream(),null, options);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
System.out.println("The Bitmap is NULL");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), mValues.get(position).getMovie(), Toast.LENGTH_SHORT).show();
}
});
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}
}
third_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
<!--removed from recycler view
app:layout_behavior="#string/appbar_scrolling_view_behavior"-->
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
recycler_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
card_view:cardCornerRadius="#dimen/margin10"
card_view:cardElevation="#dimen/margin10"
card_view:cardMaxElevation="#dimen/margin10"
card_view:contentPadding="#dimen/margin10"
card_view:cardPreventCornerOverlap="false"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="fitXY"
android:padding="5dp"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimary"
android:layout_marginTop="10dp"
android:layout_below="#+id/imageView1" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
activity_fullscreen_view_initial
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:layout_weight="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/cart_button_layout"
android:layout_alignParentTop="true"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/intial_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/imageIndicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignBottom="#+id/intial_pager"
android:layout_marginBottom="10dp" />
</LinearLayout>
</ScrollView>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="#layout/full_screen_size_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cart_button_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="bottom"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="#+id/b_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:background="#D3D3D3"
android:text="save"
android:textColor="#000000" />
<Button
android:id="#+id/b_add_to_bag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#color/colorPrimary"
android:text="add to bag"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
swipe_fragment.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">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</LinearLayout>
Try setting the setting the RecyclerView with an empty Adapter before you execute your AsyncTask.
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
new JSONTask().execute(url, this);
Then create a method in the RecyclerViewAapter to load the the populated List<JsonURLFullModel> from the AsyncTask's onPostExecute.
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
If that doesn't work trying loading on the Ui thread from Asynctask using runOnUiThread
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(...)
}
});
Edit 1 Adding loadJson to your RecyclerViewAapter.class
#Override
public int getItemCount() {
return mValues.size();
}
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
Call the method in your PostExecute
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(result.getMovieModelList());
}
});
}
Also add your the Layout manager for the RecyclerView in onCreateView
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);
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'm having problems regarding how my list is.
I have navigation drawer and the content of my list start under that navigation drawer.
´
Navigation Drawer and search view
As you can see the search view is under "EBSPMA" wich is my company logo
Then i have another error, the process dialog only hide when i touch the screen even if the process is already done.
ProgressDialod don't dismiss
This is my fragment code
public class AtividadesFragment extends ListFragment {
public AtividadesFragment(){
}
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://xxx.xx.xx/xxxx/xxxx/xxx.php";
private ProgressDialog pg;
private List<Atividades> atividadesList = new ArrayList<>();
private ListView listView;
private AtividadesAdapter atividadesAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
atividadesAdapter = new AtividadesAdapter(getActivity(),atividadesList);
listView = (ListView) getView().findViewById(android.R.id.list);
listView.setAdapter(atividadesAdapter);
pg = new ProgressDialog(getActivity());
pg.setMessage("A carregar...");
pg.show();
JsonArrayRequest atividadesReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Ir buscar os dados
VolleyLog.d("Dentro do atividadesReq", "ver");
for (int i = 0; i < response.length(); i++) {
try{
JSONObject ati = response.getJSONObject(i);
Atividades ativ = new Atividades();
ativ.setAtividade(ati.getString("atividade"));
ativ.setLocal(ati.getString("local"));
java.sql.Date dat = java.sql.Date.valueOf(ati.getString("data"));
java.sql.Time hor = java.sql.Time.valueOf(ati.getString("hora"));
ativ.setData(dat);
ativ.setHora(hor);
atividadesList.add(ativ);
}catch (JSONException e) {
e.printStackTrace();
}
atividadesAdapter.notifyDataSetChanged();
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(atividadesReq);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.atividades, container, false);
return rootView;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pg != null) {
pg.dismiss();
pg = null;
}
}
}
abd this is my layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context=".MainActivity">
<SearchView
android:id="#+id/search_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:cacheColorHint="#android:color/transparent"
android:divider="#android:color/transparent"
android:dividerHeight="5dp" >
</ListView>