I have created a Recycler view that is supposed to be created when the activity is created. Currently, when I click a button on my MainActivity, an intent launches the ListActivity which has my recyclerview but it doesn't load. I have used toast message to confirm that each method is getting called, and that I am getting the correct data from the API. If I reset the activity using the restart activity option in Android Studio the Recycler shows up and functions correctly. I don't know what I'm doing wrong.
Here is my ListActivity:
private RecyclerView myrecyclerview;
private RecyclerView.Adapter myadapter;
private RecyclerView.LayoutManager mylayoutmanager;
static RequestQueue listqueue;
static final private String url = "https://swapi.dev/api/people/";
static ArrayList<RecyclerItem> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getSupportActionBar().hide();
listqueue = Volley.newRequestQueue(this);
myrecyclerview = findViewById(R.id.characterlist);
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
parseJsonData();
}
public void parseJsonData(){
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
try {
JSONArray jsonarray = response.getJSONArray("results");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String height = jsonobject.getString("height");
String mass = jsonobject.getString("mass");
String eyecolor = jsonobject.getString("eye_color");
String birthyear = jsonobject.getString("birth_year");
//list.add(new RecyclerItem("darth vader", "200", "128", "1950", "red"));
list.add(new RecyclerItem(name, "Height: " + height, "Mass: " + mass, "Birth Year: " + birthyear, eyecolor));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
listqueue.add(request);
}
#Override
public void onCharacterClick(int position) {
String color = list.get(position).getEyecolor();
Toast.makeText(getApplicationContext(), color, Toast.LENGTH_SHORT).show();
}
} ```
Like I mentioned, once I reload the activity, it works correctly. But I want the recycler view to show when I navigate to the activity.
The problem is that the first time that the activity is create, list is empty and parseJsonData() is running on the background filling that list.
Once you reload the activiy, the list and adapter are filled therefore when you call
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
the recycler view is show. Try to do this on your parseJsonData(); after the loop ends, then create the adapter and show the rv
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
....
}
myadapter = new MyAdapter(list, this);
....
myrecyclerview.setLayoutManager(mylayoutmanager);
I hope it help for u
Creat a List
private List< TipsList > tipsLists = new ArrayList<>();
SET UP RECYCLERVIEW LIKE THIS
RecyclerView tipsRv = findViewById(R.id.tips_rv);
TipsAdapter adapter = new TipsAdapter(tipsLists, this);
tipsRv.setAdapter(adapter);
tipsRv.setHasFixedSize(true);
tipsRv.setLayoutManager(new LinearLayoutManager(this));
getDATA
public void getWallis() {
String myJSONStr = method.loadJSON();
try {
JSONObject ROOT_OBJ = new JSONObject(myJSONStr);
JSONArray MAIN_ARRAY = ROOT_OBJ.getJSONArray("ff_api");
JSONObject TIPS_OBJ = MAIN_ARRAY.getJSONObject(3);
JSONArray TIPS_ARRAY = TIPS_OBJ.getJSONArray("Tips");
for (int i = 0; i < TIPS_ARRAY.length(); i++) {
TipsList tipsList = new TipsList();
JSONObject jsonObject = TIPS_ARRAY.getJSONObject(i);
tipsList.setId(jsonObject.getInt("id"));
tipsList.setTipsTitle(jsonObject.getString("tipsTitle"));
tipsList.setTipsDec(jsonObject.getString("tipsDec"));
tipsLists.add(tipsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Related
I am creating an app for a project where you can swipe through movie names and images, for now I am just trying to get the names working but my cards will not populate with the movie names. I had some trouble with the array adapter but I think it's working now and in the correct place. I am using a library from github for the cards and it's worked for other programs just can't get it work with this. Maybe it's because of the model class? just lost when there is no real errors. Item.xml is the design of the card with it's text and background and activity_main.xml is where I reference the library. hellotext is the textview in item.xml. Any help is appreicated!
public class MainActivity extends AppCompatActivity {
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
movieList.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
Api (same class)
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
// model.setId(jsonObject1.getString("vote_average"));
model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList = new ArrayList<>();
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Update***
I fixed the null problem BUT my cards now populate with my project name so I just see one card with com.project300.populateswipecards... any help?
private ArrayList<String> al;
private ArrayAdapter<MovieModelClass> arrayAdapter;
private ArrayList<MovieModelClass> movieList = new ArrayList<>();
private int i;
String moviename = "";
Context context;
SwipeFlingAdapterView flingContainer;
private static String JSON_URL = "https://api.themoviedb.org/3/movie/popular?api_key=8099f5720bad1f61f020fdbc855f73db";
//List<MovieModelClass> movieList;
//#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
GetData getData = new GetData();
getData.execute();
//AddArray();
// ButterKnife.inject(this);
//this add is the name of the card, with each add another card is added
//adds into array
//the array has a text and a layout we create
//this layout is the card in itself textview picture ect...
//this is when it actually swipes(clicks and movies)
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
//every time a card is completely removed he just removes it from the array
//notifies the adapter of this change
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
// Log.d("LIST", "removed object!");
// movieList.remove(0);
// arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(MainActivity.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
// movieList.add();
// arrayAdapter.notifyDataSetChanged();
// Log.d("LIST", "notified");
// i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
/* View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);*/
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "click", Toast.LENGTH_SHORT).show();
}
});
}
public class GetData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
// urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(#org.jetbrains.annotations.NotNull String s){
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for(int i = 0; i< jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
MovieModelClass model = new MovieModelClass();
movieList = new ArrayList<>();
// model.setId(jsonObject1.getString("vote_average"));
// model.setName(jsonObject1.getString("title"));
// model.setImg(jsonObject1.getString("poster_path"));
moviename = jsonObject1.getString("title");
model.setName(moviename);
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
At the end of your onPostExecute() method, I see this:
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
I think you're assuming that this will update the list of cards, since earlier in onCreate() you have written this:
flingContainer.setAdapter(arrayAdapter);
However, that is not how the new keyword and Java object references work. These two adapters are completely separate, and flingContainer doesn't "see" the adapter you create in your task.
The easiest way to solve this is likely to re-set the adapter after you create it.
arrayAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
Now the problem seems to be this for loop:
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList = new ArrayList<>();
// ...
movieList.add(model);
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
You need to move the ArrayList creation and adapter logic outside of the loop.
movieList = new ArrayList<>();
for(int i = 0; i< jsonArray.length(); i++) {
// ...
movieList.add(model);
}
arrayAdapter = new ArrayAdapter<>(MainActivity.this, R.layout.item, R.id.helloText, movieList);
flingContainer.setAdapter(arrayAdapter);
I have list data recycler view and I want to make it like a table layout and dynamical. Here is the example view of the table that I want to make:
https://ibb.co/q7zYM64
And this is my condition app :
https://ibb.co/JKXwthj
and this is my main_activity.java :
public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "http://sipermata.bappedawaykanan.com/api/admin/jumlah_penduduk_kabupaten/list?year=2019";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("data");
//JSONArray array = new JSONArray(s);
for (int i = 0 ; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
String id = o.getString("id");
String kec = o.getString("kecamatan");
String avg = o.getString("avg");
//String tahun = o.getString("year");
JSONObject isitahun = o.getJSONObject("year");
Iterator<String>itr = isitahun.keys();
//for(int j = 0; j<=isitahun.length();j++){
while (itr.hasNext()){
String key = itr.next();
JSONObject a = isitahun.getJSONObject(key);
String tahun = a.getString("value");
ListItem item = new ListItem(
id, kec, avg, key, tahun
);
listItems.add(item);
}
}
adapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
You can set layout as horizontal.
recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
LinearLayoutManager horizontalLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManager);
I have a problem using Volley, I cant get data out from OnResponse mehod.
I need to use the List outside , for Fragment operations, but i couldn`t get it out from there. Maybe im doing something wrong, but i was unable to find a solution on other sites.
Can anyone help me find a solution please?
Here is my code:
public class MainActivity extends AppCompatActivity
{
private static final String JSON_URL = "http://Something/v1/Api.php?apicall=gettopics";
ListView listView;
List<Topic> topicList;
List<Topic> topicList2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listViewTopics);
topicList = new ArrayList<>();
loadTopics();
if(topicList.isEmpty())
{
TextView t = findViewById(R.id.text);
t.setText("Empty");
}
}
class TopicAdapter extends ArrayAdapter<Topic>
{
List<Topic> topicList;
public List<Topic> getTopicList() {
return topicList;
}
public TopicAdapter(List<Topic> topicList)
{
super(MainActivity.this, R.layout.layout_topic_list, topicList);
this.topicList = topicList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.layout_topic_list, null, true);
TextView textViewName = listViewItem.findViewById(R.id.textViewTitle);
final Topic topic = topicList.get(position);
textViewName.setText(topic.getTitle());
return listViewItem;
}
}
public void loadTopics() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray topicArray = obj.getJSONArray("topics");
for (int i = 0; i < topicArray.length(); i++) {
JSONObject topicObject = topicArray.getJSONObject(i);
Topic topic = new Topic(topicObject.getInt("id"),topicObject.getInt("ordering"),topicObject.getString("title"));
topicList.add(topic);
}
TopicAdapter adapter = new TopicAdapter(topicList);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Firstly in onCreate():
topicList = new ArrayList<>();
listView = (ListView) findViewById(R.id.listViewTopics);
adapter = new TopicAdapter(topicList); //note:define 'adapter' as a class field as 'listView'
listView.setAdapter(adapter);
Then in onResponse():
topicList.clear();
try{
JSONObject obj = new JSONObject(response);
JSONArray topicArray = obj.getJSONArray("topics");
for (int i = 0; i < topicArray.length(); i++) {
JSONObject topicObject = topicArray.getJSONObject(i);
Topic topic = new Topic(topicObject.getInt("id"),topicObject.getInt("ordering"),topicObject.getString("title"));
topicList.add(topic);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
I know this question has been asked so many times, but none of the solutions answered there seems to solve my problem.
Most of the solutions suggested attaching an adapter (setadapter()) and I have done that. But the problem still seems to persist.
I also checked if my listitems are empty and it isn't.
I have attached the adapter in a function loadUserAccounts().
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_accounts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Swipe to refresh
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.userSwipeRefresh);
//Recycler View
recyclerView = (RecyclerView) findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(userAccountsActivity.this));
listItems = new ArrayList<>();
recyclerViewUserAdapter = new RecyclerViewUserAdapter(listItems, userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);
//Function to load the users to the recycler view
loadUserAccounts();
/*
* Sets up a SwipeRefreshLayout.OnRefreshListener that is invoked when the user
* performs a swipe-to-refresh gesture.
*/
swipeRefresh.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i("Swipe_log: ", "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
loadUserAccounts();
}
}
);
}
and this is my loadUserAccounts() function:
/**
* Function to load the user account
* into the recycler view from the log database
*/
public void loadUserAccounts(){
String tag_string_req = "req_user_acc";
clear();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_USER_ACCOUNTS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jArray = new JSONArray(response);
for(int i = jArray.length()-1; i>=0; i--){
JSONObject log = jArray.getJSONObject(i);
String name = log.getString("name");
String cpfNumber = log.getString("cpfNumber");
String type = log.getString("type");
String created_at = log.getString("created_at");
Log.d("Adapter: ", name + cpfNumber + type + created_at);
ListItem_RecyclerView_User item = new ListItem_RecyclerView_User (name, cpfNumber, type, created_at);
listItems.add(item);
}
recyclerViewUserAdapter.updateDataList(responseList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error!=null && error.getMessage() !=null){
Log.e(TAG,"User Accounts Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Something went wrong",Toast.LENGTH_LONG).show();
}
}
});
//Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
if (swipeRefresh == null)
return;
else {
if (swipeRefresh.isRefreshing()) {
swipeRefresh.setRefreshing(false);
}
}
}
My adapter class RecyclerViewUserAdapter
public class RecyclerViewUserAdapter extends RecyclerView.Adapter<RecyclerViewUserAdapter.ViewHolder> {
private List<ListItem_RecyclerView_User> listItems;
private Context context;
public RecyclerViewUserAdapter(List<ListItem_RecyclerView_User> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
public void updateDataList(List<ListItem_RecyclerView_User> newDatas) {
listItems.clear();
listItems.addAll(newDatas);
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_recycler_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewUserAdapter.ViewHolder holder, int position) {
ListItem_RecyclerView_User listItem = listItems.get(position);
holder.txtUserName.setText(listItem.getTxtUserName());
holder.txtUserCpf.setText(listItem.getTxtUserCpf());
holder.txtAccountType.setText(listItem.getTxtAccountType());
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
date = df.parse(listItem.getTxtCreatedDate());
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String loginTime = sdf.format(date);
holder.txtCreatedDate.setText(loginTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView txtUserName;
private TextView txtUserCpf;
private TextView txtAccountType;
private TextView txtCreatedDate;
public ViewHolder(View itemView) {
super(itemView);
txtUserName = (TextView) itemView.findViewById(R.id.txtUserName);
txtUserCpf = (TextView) itemView.findViewById(R.id.txtUserCpf);
txtAccountType = (TextView) itemView.findViewById(R.id.txtAccountType);
txtCreatedDate = (TextView) itemView.findViewById(R.id.txtCreatedDate);
}
}
}
Try this...
modify that getItemCount() to like this.
#Override
public int getItemCount() {
return listItems.size();
}
Try this
Create your adapter with empty list data
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
// your normal code
recyclerView = (RecyclerView) findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(userAccountsActivity.this));
listItems = new ArrayList<>();
// create new adapter
recyclerViewUserAdapter = new RecyclerViewUserAdapter(new ArrayList<>(), userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);
//your normal code
}
In your response
#Override
public void onResponse(String response) {
try {
List<ListItem_RecyclerView_User> responseList = new ArrayList<>();
JSONArray jArray = new JSONArray(response);
for(int i = jArray.length()-1; i>=0; i--){
JSONObject log = jArray.getJSONObject(i);
String name = log.getString("name");
String cpfNumber = log.getString("cpfNumber");
String type = log.getString("type");
String created_at = log.getString("created_at");
Log.d("Adapter: ", name + cpfNumber + type + created_at);
ListItem_RecyclerView_User item = new ListItem_RecyclerView_User (name, cpfNumber, type, created_at);
responseList.add(item);
}
/*recyclerViewUserAdapter = new RecyclerViewUserAdapter(listItems, userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);*/
// write method to update your data
recyclerViewUserAdapter.updateDataList(responseList);
} catch (JSONException e) {
e.printStackTrace();
}
}
In your adapter create method
public void updateDataList(List<ListItem_RecyclerView_User> newDatas) {
listItems.clear();
listItems.addAll(newDatas);
notifyDataSetChanged():
}
In Activity B there has a spinner where the data were get from MySQL (Table location).
Activity B
private ArrayList<String> froms;
private JSONArray resultFrom;
public void addItemsOnFrom() {
travelFrom = (Spinner) findViewById(R.id.travelFrom);
StringRequest stringRequest = new StringRequest(Configs.FROM_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultFrom = j.getJSONArray(Configs.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getFrom(resultFrom);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getFrom(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
froms.add(json.getString(Configs.TAG_LOCATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}
When save button is clicked, it will return the selected value(OFFICE) to Activity A listView. And in Activity A, when the list is pressed, it will intent to Activity B. In this time, the spinner in Activity B will display the selected item first(OFFICE).
**Table location** // table location has 2 data
NONE
OFFICE
Assume OFFICE is selected in B. When list is clicked, I want OFFICE display first in spinner B.
Code in Activity B for display OFFICE first.
if(getIntent().getExtras()!=null)
{
final String from = getIntent().getStringExtra("from");
selectedItemFrom(from);
}
public void selectedItemFrom(final String value)// display OFFICE first
{
travelFrom = (Spinner) findViewById(R.id.travelFrom);
StringRequest stringRequest = new StringRequest(Configs.FROM_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Configs.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getFrom(result, value);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getFrom(JSONArray j, String value) {
int position = 0;
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
froms.add(json.getString(Configs.TAG_LOCATION));
if (froms.get(i).equalsIgnoreCase(value)) {
position = i;
//Toast.makeText(getApplicationContext(),position+"",Toast.LENGTH_LONG).show();
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
travelFrom.setSelection(position);
}
The OFFICE can display first, but the problem is when I checked the spinner B, it shows NONE,OFFICE,NONE OFFICE ..Why the spinner data will get duplicated ? Thanks
I think problem is in this line travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));...But how to solve??? Anyone?
And sometimes the spinner will display the selected item first but sometimes it will not...What are the better way to write?
Edit
{"result":[{"name":"NONE"},{"name":"OFFICE"}]}
I put forms.clear in beginning of both getFrom method now. But the problem is when I select NONE and return to A, then goes to B again,the spinner now has NONE only...
Please try something like this.
This activity will expect a Intent with the key "from" that is set to either "NONE" or "OFFICE". If the intent does not have the data, then it will default to whatever was inserted into the Spinner first.
public class MainActivity extends AppCompatActivity {
private Spinner travelFrom;
private ArrayAdapter<String> mSpinnerAdapter;
private List<String> mSpinnerData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String from = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
from = extras.getString("from");
}
setupFromSpinner(from);
}
private void setupFromSpinner(final String value) {
travelFrom = (Spinner) findViewById(R.id.travelFrom);
mSpinnerData = new ArrayList<String>();
mSpinnerAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, mSpinnerData);
mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
travelFrom.setAdapter(mSpinnerAdapter);
JsonObjectRequest req = new JsonObjectRequest(Configs.FROM_URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mSpinnerData.clear();
try {
JSONArray resultFrom = response.getJSONArray("result");
for (int i = 0; i < resultFrom.length(); i++) {
JSONObject fromObj = resultFrom.getJSONObject(i);
String name = fromObj.getString("name");
mSpinnerData.add(name);
}
mSpinnerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
if (value != null) {
int position = mSpinnerAdapter.getPosition(value);
travelFrom.setSelection(position);
} else {
travelFrom.setSelection(0);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(req);
}
}
add froms.clear() to this piece of code;
private void getFrom(JSONArray j) {
//Traversing through all the items in the json array
froms.clear();
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
froms.add(json.getString(Configs.TAG_LOCATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
travelFrom.setAdapter(new ArrayAdapter<String>(Add_Details_Information.this, android.R.layout.simple_spinner_dropdown_item, froms));
}