I have an app contains a recyclerview the code works correctly but the data repeat itself in the list when I want to parse Json into Android Studio
how can I fix that while the data is coming from internet
but when I use a normal ListView it is working great
and I am using same adapter
and this is my code
private RecyclerView recyclerView;
private RecyclerViewAdapter recyclerView_dAdapter;
public List<List_Item> listItems = new ArrayList<>();
private GridLayoutManager gridLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.m_RecyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(this, 1);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView_dAdapter = new RecyclerViewAdapter(listItems, this);
recyclerView.setAdapter(recyclerView_dAdapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (gridLayoutManager.findLastCompletelyVisibleItemPosition() == listItems.size() - 1) {
Get_All_Users(listItems.get(listItems.size()-1).getId());
}
}
});
Get_All_Users(0);
}
public void Get_All_Users(int limit) {
CheckInternetConnection cic = new CheckInternetConnection(getApplicationContext());
Boolean Ch = cic.isConnectingToInternet();
if (!Ch) {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
} else {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
"https://raw.githubusercontent.com/abodali/ox/master/f.txt?limit" + limit
,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonResponse = jsonArray.getJSONObject(0);
JSONArray jsonArray_usersS = jsonResponse.getJSONArray("All_storys");
for (int i = 0; i < jsonArray_usersS.length(); i++) {
JSONObject responsS = jsonArray_usersS.getJSONObject(i);
int id = responsS.getInt("id");
String story = responsS.getString("story_name");
String img_link = responsS.getString("img_link");
listItems.add(new List_Item(id, story, img_link));
}
recyclerView_dAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
stringRequest.setShouldCache(false);
}
}
}
Kind Regards
When you get a new response, you are not clearing your list before adding your new data. I'm assuming that this is what you want.
So before your for-loop, add a line in there that will clear your list:
listItems.clear();
Related
Hi i have successfully retrieved some data from my php url from my database but am stuck at trying to get data for specific date using date picker the code below am able to get data of the current day but how do i get data using date picker on the floating action button.
I have placed the material date picker but how do i parse or filter the json data using the date that i obtain from the date pickerclick listener.
public class MainActivity extends AppCompatActivity {
private ArrayList<Games> gamesList;
private GamesAdapter mGamesAdapter;
//the recyclerview
private RecyclerView recyclerView;
private RequestQueue mRequestQueue;
private SwipeRefreshLayout swipeRefreshLayout;
private FloatingActionButton floatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
floatingActionButton = findViewById(R.id.floatingActionButton);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
gamesList = new ArrayList<>();
mGamesAdapter = new GamesAdapter(this, gamesList);
recyclerView.setAdapter(mGamesAdapter);
swipeRefreshLayout = findViewById(R.id.swipelayout);
swipeRefreshLayout.setColorSchemeResources(R.color.blue, R.color.lightBlue, R.color.deepPurple,
R.color.purple, R.color.pink, R.color.orange, R.color.red);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
loadGames();
//swipeRefreshLayout.setRefreshing(true);
Toast.makeText(MainActivity.this, "Swipe down to Refresh the matches.", Toast.LENGTH_SHORT).show();
}
});
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
Long today = MaterialDatePicker.todayInUtcMilliseconds();
//Material Date Picker
MaterialDatePicker.Builder builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText("SELECT A DATE");
builder.setSelection(today);
MaterialDatePicker materialDatePicker = builder.build();
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(), "DATE_PICKER");
}
});
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
// mTextView.setText("Selected Date : "+materialDatePicker.getHeaderText());
}
});
mRequestQueue = Volley.newRequestQueue(this);
}
#Override
protected void onStart() {
loadGames();
super.onStart();
}
private void loadGames() {
swipeRefreshLayout.setRefreshing(true);
final String today_date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
String urlJsonObj = "https://surebetsapp.com/json_get_data.php";
gamesList.clear();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, urlJsonObj, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("server_response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject serverResponse = jsonArray.getJSONObject(i);
Games game = new Games();
game.country = serverResponse.getString("league");
//game.league = serverResponse.getString("country");
game.home = serverResponse.getString("home_team");
game.away = serverResponse.getString("away_team");
game.tip = serverResponse.getString("pick");
//game.odd = serverResponse.getString("bet_odds");
game.time = serverResponse.getString("m_time");
game.result = serverResponse.getString("outcome");
game.outcome = serverResponse.getString("result");
game.logo = serverResponse.getString("league_logo");
game.h_logo = serverResponse.getString("h_logo_path");
game.a_logo = serverResponse.getString("a_logo_path");
String date = serverResponse.getString("m_date");
String mDate = date.substring(0, 10);
if (mDate.equals(today_date)) {
gamesList.add(game);
}/* else (mDate.equals()) {
}*/
mGamesAdapter.notifyDataSetChanged();
//gamesList.add(new Games(time, country, tip, league, home, away, odd, result, outcome, logo, h_logo, a_logo));
}
//mGamesAdapter = new GamesAdapter(MainActivity.this, gamesList);
//recyclerView.setAdapter(mGamesAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false);
Log.d(TAG, "onErrorResponse: "+error);
}
});
mRequestQueue.add(request);
}
Using Volley, I was able to make a asynchronous HTTP GET call to my API that i wanted to hit. But it is taking 15 to 20 seconds to fetch the data and populate it on the UI, Staggered Grid Layout using Recycler View.
For every search call I make, it roughly takes that much time which is bad. How do I reduce this latency? I also added the RequestQueue but no luck.
I'm initializing the Adapter after the search call is made. Is it a good approach to do it there? Or would you recommend doing it in onCreate method of activity. Could anyone please guide what's the cause for this latency?
Here's the excerpt from the code
public class StaggeredSearchActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private StaggeredGridAdapter staggeredGridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_staggered_search);
Intent intent = getIntent();
String searchText = intent.getStringExtra("searchText");
getSearchData(searchText);
recyclerView = findViewById(R.id.staggered_recycler_view);
staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
}
private void getSearchData(String searchText) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = "https://my-json-server.typicode.com/typicode/demo/comments";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
ArrayList<StaggeredCustomCard> dataset = new ArrayList<>();
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("tweets");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String body = jsonObject.getString("body");
String postId = jsonObject.getString("postId");
dataset.add(new StaggeredCustomCard(body, postId);
}
staggeredGridAdapter = new StaggeredGridAdapter(StaggeredSearchActivity.this, dataset);
recyclerView.setAdapter(staggeredGridAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
...
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
}
}
In my android app I want to fetch JSON data from a website.
I created it to fetch data with this structure:
[{"id":"1","name":"a"},{"id":"2","name":"a"},{"id":"3","name":"a"},{"id":"4","name":"a"}]
It works perfectly like it should. Now I tried to manipulate the code a little to fetch other JSON data.it has this structure:
{"ok":true,"license":"xx","data":"zz","status":"ok","stations":
[{"id":"474","name":"ABC","street":"MARGARETE-STR."},
{"id":"442","name":"XYZ","street":"ABCSTR"}]}
I don‘t get any results for it, I thought it might be because the data that should be fetched lays in an array, but I thought as well that I am getting it anyway. Am I fetching it the wrong way?
My code:
public class MainActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
String GET_JSON_DATA_HTTP_URL = "xx.com";
String JSON_ID = "id";
String JSON_NAME = "name";
String JSON_SUBJECT = "email";
String JSON_STREET = "street";
Button button;
JsonArrayRequest jsonArrayRequest;
com.android.volley.RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
button = (Button) findViewById(R.id.button);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});
}
public void JSON_DATA_WEB_CALL() {
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(JSON_ID));
GetDataAdapter2.setName(json.getString(JSON_NAME));
GetDataAdapter2.setStreet(json.getString(JSON_STREET));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
The second JSON sample is not a JSON array; it is a JSON object. You should use a JsonObjectRequest instead of a JsonArrayRequest to obtain this data.
Hey i'm creating Android application which connect with my database MySQL. I created an ArrayList with categories and added it to Adapter and then to Spinner. I see Spinner items but after onClick nothing happens and when I try to check what is in my ArrayList I see that it is empty.Data downloaded.
After click in Spinner nothing change
Here is my code:
public class InsertProductActivity extends AppCompatActivity {
Spinner categories;
String categoriesURL = "myURL";
ArrayList<String> downloadedCategories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_product);
categories = findViewById(R.id.categories);
getCategories();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
}
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
for(int i=0;i<jsonArray.length();i++){
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
}
try this one.
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
downloadedCategories = new ArrayList<>(); // try to add your instantiation of your arrayList here.
for(int i=0;i<jsonArray.length();i++) {
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//this block of code will prompt after your downloadedCategories finish storing your objects to your arrayList because if you put this in onCreate this wil call before your getCategories process not finish yet. So much better its much safer here.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
requestQueue.add(jsonObjectRequest);
}
I have figured out that my main issue right now is my intent code. I have no idea how to build my intent to make the data come back from the website so if anyone could help me with that, it would be awesome! I am trying to get JSON data from the openweather api and my app will load up the web page instead of bringing it into the list view. Right now with the intent I have, a web page opens up with the data I need. Any help would be great!
public class MainActivity extends AppCompatActivity {
private String url = "http://api.openweathermap.org/data/2.5/weather?q=London,us&APPID=805bd9f830268d5274c60e41613c28a5";
private List<String> items = new ArrayList<String>();
private ArrayAdapter<String> mArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btnRequest = (Button) findViewById(R.id.button); //your button id must be button
final ListView lv = (ListView) findViewById(R.id.listView); //your listview ide must be listview
final RequestQueue requestQueue = Volley.newRequestQueue(this);
final JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jcity = response.getJSONObject("city");
String name = jcity.getString("name");
JSONArray wlist = response.getJSONArray("list");
for (int i = 0; i < 10; i++) {
JSONObject jsonObject = wlist.getJSONObject(i);
String dt = jsonObject.getString("dt");
JSONArray warray = jsonObject.getJSONArray("weather");
JSONObject wobj = warray.getJSONObject(0);
String desc = wobj.getString("description");
items.add(dt + " " + desc);
Log.d("date", dt); //Log.d prints to the terminal
Log.d("desc", desc);//good for debugging
}
mArrayAdapter = new ArrayAdapter<String>
(getApplicationContext(),
android.R.layout.simple_list_item_1, items);
//lv.setAdapter(mArrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
btnRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestQueue.add(jor);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
}
I think that's because you missed the setting adapter to the ListView. And also make sure your items have data inside it .
mArrayAdapter = new ArrayAdapter<String> (getApplicationContext(), android.R.layout.simple_list_item_1, items);
lv.setAdapter(mArrayAdapter);