Invalid view holder adapter while trying to call notifydatasetchanged() in recyclerview - android

My Recyclerview was working fine , what i did was simple, i fetched data from a webervice and displayed it using recyclerView
This is my code for loading more data
public void loadmoredata(int limit) {
limit++;
String url = "http://oilpeople.talenetic.com/api/SearchJob?limit="+limit+ "&jobkeyword=" + key + "&countrytext=" + coun + "&location=" +loc+ "&apikey=1111111111&siteid=1";
JsonObjectRequest loadmore = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray(loadArray);
jobTitle = new String[jsonArray.length()];
salary = new String[jsonArray.length()];
companyName = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
if(loadArray.equals("Indeedjobslist")) {
String salaryLoc = c.getString("location");
jobTitle[i] = c.getString("jobtitle");
companyName[i] = c.getString("companyname");
salary[i] = salaryLoc;
} else {
String salaryLoc = c.getString("salary")+ " \u2022 " +c.getString("location");
jobTitle[i] = c.getString("jobtitle");
companyName[i] = c.getString("companyname");
salary[i] = salaryLoc;
}
// show the values in our logcat
m.setCompanyName(companyName);
m.setJobTitle(jobTitle);
m.setSalary(salary);
adapter.notifyDataSetChanged();
}
} catch(JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(SearchResults.this).add(loadmore);
}
adapter is a global variable. I am trying to load more data like this:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.fTextView.setText(jobTitle[position]);
holder.mTextView.setText(companyName[position]);
holder.sTextView.setText(jobs[position]);
if (position % 10 == 0) {
int limit = position + 5;
loadmoredata(limit);
}
}
Whenever the % of position is 0 I load more data, but I am getting indexoutofBounds error.

remove
if (position % 10 == 0) {
int limit = position + 5;
loadmoredata(limit);
}
and use this method calling to know count from your main activity then call your above cod but i think that will cause infinite loop
public int getItemCount() {
return mDataset.length;
}

Related

Cannot assign variables when doing JSON in android studio

I want to execute taking data from JSON as shown below. But when
Toast.makeText(this, MangIDtrailer.size () + "..... check size of Array IDtrailer .....", Toast.LENGTH_LONG).show();
it returns 0.
I don't know what the cause is.
public class Main2Activity extends AppCompatActivity {
ListView Listmovie;
ArrayList<String> MangIDtrailer;
public static ArrayList<InfoMovie> inforMovieArrayList;
AdapterMovie adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
String url1 ="http://the....ying";
inforMovieArrayList = new ArrayList<>();
MangIDtrailer = new ArrayList<>();
MangIDtrailer = GetIDMovie(url1);
inforMovieArrayList = DataMovie(MangIDtrailer);
Listmovie = (ListView) findViewById(R.id.ListMovie);
adapter = new AdapterMovie(this, R.layout.movielist, inforMovieArrayList);
Listmovie.setAdapter(adapter);
Listmovie.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(Main2Activity.this,Review_Movie.class);
intent.putExtra("IDmovie",i);
//Toast.makeText(MainActivity.this, ""+i, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}
public ArrayList<String> GetIDMovie (String Url) {
final ArrayList<String> ArrayID = new ArrayList<>();
final RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, Url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String IDTrailer;
JSONArray jsonArrayFreeMovies = response.getJSONArray("FreeMovies");
for (int i=0; i < jsonArrayFreeMovies.length(); i++) {
JSONObject jsonObjectFreeMovies = jsonArrayFreeMovies.getJSONObject(i);
IDTrailer = jsonObjectFreeMovies.getString("trailer_id");
ArrayID.add(IDTrailer);
Toast.makeText(Main2Activity.this, i+"************", Toast.LENGTH_SHORT).show();
}
Toast.makeText(Main2Activity.this, MangIDtrailer.get(2)+"check Data ", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(jsonObjectRequest);
queue.cancelAll(jsonObjectRequest);
return ArrayID;
}
public ArrayList <InfoMovie> DataMovie (ArrayList<String> MangIDtrailer) {
final ArrayList<InfoMovie> inforMovieArray = new ArrayList<>();
final String linkDetail = "http://tk/api/trailers/movDetail?trailer_id=";
final RequestQueue queue2 = Volley.newRequestQueue(this);
//////////////Check that MangIDtrailer.size () has no data////////////////////////////////////
Toast.makeText(this, MangIDtrailer.size()+".....check size of Array IDtrailer .....",Toast.LENGTH_LONG).show();
for (int i=0; i<MangIDtrailer.size(); i++) {
JsonObjectRequest jsonObjectRequest2 = new JsonObjectRequest(Request.Method.GET, linkDetail + MangIDtrailer.get(i) + "&test_fullVer=1", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String linkposter, linkbackdrop, namemovie, overviewmovie, Release_date, Urltrailer;
Float Vote_average;
String linkHot = "https://image.tmdb.org/t/p/w500/";
JSONObject jsonObjectInfo = null, jsonObjectMore = null;
JSONObject jsonopFreeMovies1 = response.getJSONObject("FreeMovies");
if (jsonopFreeMovies1.has("FreeMovies")) {
//Toast.makeText(MainActivity.this, "Cos ", Toast.LENGTH_SHORT).show();
JSONObject jsonObjectFreeMovies2 = jsonopFreeMovies1.getJSONObject("FreeMovies");
jsonObjectInfo = jsonObjectFreeMovies2.getJSONObject("Info");
jsonObjectMore = jsonObjectFreeMovies2.getJSONObject("More");
} else {
//Toast.makeText(MainActivity.this, "Khoong cos", Toast.LENGTH_SHORT).show();
jsonObjectInfo = jsonopFreeMovies1.getJSONObject("Info");
jsonObjectMore = jsonopFreeMovies1.getJSONObject("More");
}
namemovie = jsonObjectInfo.getString("title");
Urltrailer = jsonObjectInfo.getString("trailer_urls");
linkposter = linkHot + jsonObjectInfo.getString("thumbnail");
overviewmovie = jsonObjectMore.getString("overview");
linkbackdrop = linkHot + jsonObjectMore.getString("backdrop_path");
Release_date = jsonObjectMore.getString("release_date");
Vote_average = Float.valueOf(jsonObjectMore.getLong("vote_average"));
inforMovieArray.add(new InfoMovie(namemovie, overviewmovie, linkposter, linkbackdrop, Vote_average, Release_date));
Toast.makeText(Main2Activity.this,namemovie + "-" + overviewmovie + "-" + Vote_average, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(Main2Activity.this, "Lỗi", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this, "Lỗi Try catch", Toast.LENGTH_SHORT).show();
}
});
queue2.add(jsonObjectRequest2);
}
return inforMovieArray;
}
}
As you suggested
Toast.makeText(this, MangIDtrailer.size()+".....check size of Array IDtrailer .....",Toast.LENGTH_LONG).show();
This is where you are getting size zero, which is absolutely true, because you have only initialized your array MangIDtrailer and it is an empty array. Your function GetIDMovie(url1); has a loop which populates your MangIDtrailer array which is below where you have called the toast. So your array is empty and thus its size returns zero.
One handy tip for you, you should name your functions in camelCase with first letter of your word in lowercase. GetIDMovie(url1) seems more like a class constructor. :)
EDIT:
The above solves your initial problem.
To fully solve your problem, you have to understand that Network Operations are asynchronous, meaning they will execute after sometime or they may return no value at all depending on various conditions, like network bandwidth, your server state, the parameters passed to your HTTP requests, etc.
You have two network calls in your above code; in functions: GetIDMovie() and DataMovie(). The second function requires an array of IDs which is only available if your first request is complete and returns an array of ids. So what you would want to do is, only after you get the array of ids ie. in onResponse of GetIDMovie() after the for loop, you should make a call to DataMovie().
This however is really ugly solution. I hope you will research further for better solution.

Obtaining an array of json format question and put them into an array in android studio

The goal here is to retrieve JSON format data from an API, convert the data into an array in android studio. Then to display a random question into a text view and the question will not repeat itself. The question changes everytime a button is clicked. There's something wrong with the logic of how I use my array/parsing the data to the array. I am not sure how to proceed. Any help is appreciated
MY JSON format
{
"error": false,
"message": "Successfully retrieved",
"questions": [
{
"question": "Tell us about yourself?"
},
{
"question": "Tell us about yourself2?"
},
{
"question": "Tell us about yourself3?"
},
{
"question": "Tell us about yourself4?"
},
{
"question": "Tell us about yourself5?"
}
]
}
My code so far ( simplified to this function )
public class MainActivity extends AppCompatActivity {
// create arraylist to store question
List<String> questionList = new ArrayList<>();
// use max to decide the number of question
// use i to find out the number of questions
int i = 10;
int min = 0;
int max = i;
int[] usedInt = new int[max];
//create another array to put all the used integer inside for 0 repeition of question
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textViewQuestions = (TextView) findViewById(R.id.questionView);
usedInt = new int[i];
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
//generate random number, set textview the question, set int to usedint array
textViewQuestions.setText(questionList.get(i1));
usedInt[0] = i1;
//set first question
findViewById(R.id.changeQuestion).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d(TAG,questionList[updateQuestions(usedInt)]);
//final int[] usedIntTemp = usedInt;
getQuestions();
int n = updateQuestions(usedInt);
textViewQuestions.setText(questionList.get(n));
//finish();
}
});
}
}
public int updateQuestions(int usedInteger[]) {
int min = 0;
int max = i;
Random r = new Random();
int i2 = r.nextInt(max - min + 1) + min;
int uInteger[] = usedInteger;
int l = 0;
while (l != max) {
if (i2 == usedInteger[l]) {
l++;
if (l == max) {
Toast.makeText(getApplicationContext(), "No other questions available", Toast.LENGTH_LONG).show();
}
} else {
usedInteger[usedInteger.length + 1] = i2;
return i2;
}
}
return i2;
}
private void getQuestions()
{
class GetQuestions extends AsyncTask<Void, Void, String> {
//private ProgressBar progressBar;
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("role_id", "1");
//returing the response
return requestHandler.sendPostRequest(URLs.URL_QUESTIONS, params);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//displaying the progress bar while user registers on the server
//progressBar = (ProgressBar) findViewById(R.id.progressBar);
//progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//hiding the progressbar after completion
//progressBar.setVisibility(View.GONE);
boolean Error1 = false;
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//HashMap<String, String> questionJson = new HashMap<>();
// success = obj.getBoolean("error");
if (!obj.getBoolean("error")) {
//Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the questions from the response
JSONArray questionsJson = obj.getJSONArray("questions");
//creating a new questions object
for (i = 0; i < questionsJson.length(); i++) {
JSONObject object = questionsJson.getJSONObject(i);
questionList.add(object.getString("question"));
Log.d(TAG,"objcheck");
Log.d(TAG,object.getString("question"));
//q = c.getString("question");
//questionJson.put("question", q);
//questionList.add(questionJson);
}
finish();
//startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
GetQuestions gq = new GetQuestions();
gq.execute();
}
Object[] array = new Object[10]; // say 10 objects
int remain = array.length;
Random rnd = new Random();
public Object next () {
if (remain == 0) {
return null;
} else {
int i = rnd.nextInt(remain--);
Object tmp = array[i];
array[i] = array[remain];
array[remain] = tmp;
return tmp;
}
}
This will generate next random question
I tried this, with
getQuestions();
String n = String.valueOf(next());
textViewQuestions.setText(n);
I also populated the array like this
for (i = 0; i < questionsJson.length(); i++) {
JSONObject object = questionsJson.getJSONObject(i);
array[i] = object.getString("question");
questionList.add(object.getString("question"));
Log.d(TAG,object.getString("question"));
}
However, the questions do repeat but will only show a set amount of questions. :( How to make the questions not repeat?

How to sort data based on a parameter obtained from JSON through Getter and Setter multiples times using button

I want to save the ArrayList thatt is formed using getter and setter when I run my AsyncTask first time. It fetches json data and I uses that via getter and setter.
Now I have three sorting buttons. I want when first time date is populated it gets stored and I can apply sorting on array list and pass that sorted list to post execute.
What I did - used a boolen var to know if it's first run and modify it accordingly. I globally defined my array list and model.
Following is doInBackground()
protected List<service_detail_model> doInBackground(String... strings) {
serviceModelList = new ArrayList<>();
if (!dataSet) {
dataSet=true;
ServiceURL = ServiceURL + "type=" + type + "&city=" + city + "&orderby=" + orderby + "&origin=" + origin;
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(ServiceURL);
Log.e("kkkk", jsonStr);
if (jsonStr != null) {
try {
JSONArray listArray = new JSONArray(jsonStr);
for (int i = 0; i < listArray.length(); i++) {
JSONObject serviceObject = listArray.getJSONObject(i);
serviceModel = new service_detail_model();
serviceModel.setName(serviceObject.getString("name"));
serviceModel.setPhone(serviceObject.getString("phone"));
serviceModel.setImage(serviceObject.getString("img"));
serviceModel.setPer(serviceObject.getString("per"));
serviceModel.setPrice(serviceObject.getInt("price"));
serviceModel.setRating(serviceObject.getInt("rating"));
serviceModel.setDist(serviceObject.getInt("dist"));
serviceModelList.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
else{
if (orderby.equals("location")) {
Log.e("ll", String.valueOf(serviceModelList.get(0).getDist()));
Collections.sort(serviceModelList, new Comparator<service_detail_model>() {
#Override
public int compare(service_detail_model o1, service_detail_model o2) {
return o1.getDist() - o2.getDist();
}
});
}
else if (orderby.equals("price")) {
Collections.sort(serviceModelList, new Comparator<service_detail_model>() {
#Override
public int compare(service_detail_model o1, service_detail_model o2) {
return o1.getPrice() - o2.getPrice();
}
});
}
else if (orderby.equals("rating")) {
Collections.sort(serviceModelList, new Comparator<service_detail_model>() {
#Override
public int compare(service_detail_model o1, service_detail_model o2) {
return (int) (o1.getRating()*100 - o2.getRating()*100);
}
});
}
}
return serviceModelList;
}
When I did debugging I found that list size is 0.

RecyclerView chat load more items from top

I am trying to implement pagination in recyclerview to load more chat messages when the user scrolls to top , this is achieved by sending the last message time i.e coversations[0] time to the API , but when the new list is added the old List gets repeated many times . I think this is because i am not updating the time properly , What is the correct way to achieve this?
This is the code i am using, first time i am setting the flag to false and time as empty.
getConvoData(k, " ", "", false);
private String last_msg_time = " ";
private Boolean flag = false;
rv_convo.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(-1)) {
if (conversations != null) {
String time = last_msg_time;
getConvoData(k, " ", time, true);
}
}
}
});
this is the method for fetching conversation Data
private void getConvoData(final String k, final String new_message, final String last_time, final boolean flag) {
final String token1 = Global.shared().tb_token;
final String url = "https://app.aer.media/v2/message_router/_getChat";
final JSONObject jsonBody = new JSONObject();
final ProgressDialog progressDialog = new ProgressDialog(this);
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
final JSONObject data = jObj.getJSONObject("data");
conversations = data.getJSONArray("conversation");
JSONObject for_chat = data.getJSONObject("for_chat");
JSONArray jsonArr_chat = new JSONArray();
jsonArr_chat.put(for_chat);
params = (RelativeLayout.LayoutParams) rv_convo.getLayoutParams();
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
if (!flag) {
convobeans = gson.fromJson(conversations.toString(), convType);
last_msg_time = conversations.getJSONObject(0).getString("time");
Log.d("OldList", convobeans.toString());
adapter = new ChatDetailsAdapter(forChatBeen, convobeans, ChatDetailsActivity.this, forChatBeansList, image, name, initials, new_message, bitmap);
// Collections.reverse(convobeans);
rv_convo.setAdapter(adapter);
rv_convo.smoothScrollToPosition( rv_convo.getAdapter().getItemCount() - 1);
adapter.notifyDataSetChanged();
rv_convo.setNestedScrollingEnabled(true);
} else {
newConvo = gson.fromJson(conversations.toString(), convType);
last_msg_time = conversations.getJSONObject(0).getString("time");
if (newConvo != null && newConvo.size() > 0) {
Log.d("newList", newConvo.toString());
convobeans.addAll(0, newConvo);
adapter.notifyItemChanged(0, newConvo.size());
}
}
}
}
}
Depending on the flag I am updating the list and updating the time as well but the list gets repeated in the RecyclerView due to the previous time being passed , how do I update the time optimally and fetch the new list each time?
This code is used to fetch the data when the user scroll down in a recylerview. Just analyze this code you will get the basic idea.
rvCategory.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) {
visibleItemCount = mLinearLayoutManager.getChildCount();
totalItemCount = mLinearLayoutManager.getItemCount();
pastVisiblesItems = mLinearLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
loading = false;
fetchData();
}
}
}
}
});
Function FetchData()
private void fetchData() {
String url = EndPoints.location + "getMobileData.php?lastData=" + lastData;
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
lastData = response.getString("last");
JSONArray jArray = response.getJSONArray("response");
if (jArray.length() == 0) {
//Empty condition
} else {
for (int i = 0; i < jArray.length(); i++) {
//Append the chat with the Dataobject of your modelAnd swap the recylerview view with new data
//Example
}
adapter.swap(rvHomeModel.createHomeList(DataPathsHome, true));
}
} catch (JSONException e) {
e.printStackTrace();
}
loading = true;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
loading = true;
Toast.makeText(CategoryView.this, "No internet connection", Toast.LENGTH_LONG).show();
}
});
// Add a request (in this example, called stringRequest) to your RequestQueue.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
}
Create a function called swap in your adapter class that accept the new dataset
public void swap(List<rvHomeModel> list) {
//Check your previouse dataset used in adapter is empty or not
if (rvHomeModels!= null) {
rvHomeModels.clear();
rvHomeModels.addAll(list);
} else {
rvHomeModels = list;
}
notifyDataSetChanged();
}
At server
1. Get the previous value
2. Do the database operation and get the chats id < of previous
2. Create a JSON Object contain
{
last:last_chat_id,
response:{
//Your chat
}
}
This is not a perfect solution for this question. But you will get the basic idea about what you are looking for.

Append data in ListView while scrolling but the focus of screen changes after every append

I am trying to load data from api and trying to list only 10 item at a time and when i reach the bottom of list then i should load next 10 data on list and so on.
But when the data is loaded the list is scrolled back to the top, but i want that the focus of list should be remain unchanged just the next data should load.
here is the code :
lvCategory = (ListView) myFragmentView.findViewById(R.id.lvCategory);
lvCategory.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
private LinearLayout lBelow;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
/** To do code here*/
Toast.makeText(getContext(), "end of scroll", Toast.LENGTH_SHORT).show();
pageno++;
getListData(pageno);
Toast.makeText(getContext(), "set focus before", Toast.LENGTH_SHORT).show();
lvCategory.setSelection(5);
Toast.makeText(getContext(), "set focus after", Toast.LENGTH_SHORT).show();
lvCategory.smoothScrollToPosition(11);
}
}
});
getListData(pageno);
and here is the code of getlistData
private void getListData(int pageNo) {
//String url = "http://httpbin.org/get?site=code&network=tutsplus";
// String url = "http://52.27.73.255/api/index.php/product/category/get/1/10";
// Request a string response
//List<Category> categoryList;
String noOfEntry ="10";
if(pageNo==1){
categoryList = new ArrayList<>();
}
String url = "http://52.27.73.255/api/index.php/product/category/get/"+pageNo+"/"+noOfEntry;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
// String def = response.getString("url");
//response = response.getJSONObject("args");
String code = response.getString("code");
if(code.equals("1")) {
jsonArray = response.getJSONArray("document");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject finalObject = jsonArray.getJSONObject(i);
Category category = new Category();
category.setCategoryID(finalObject.getString("CategoryID"));
category.setCategoryCompanyID(finalObject.getString("CategoryCompanyID"));
category.setCategoryName(finalObject.getString("CategoryName"));
category.setCategoryLogo(finalObject.getString("CategoryLogo"));
category.setCategoryIsActive(finalObject.getString("CategoryIsActive"));
category.setCategoryDescription(finalObject.getString("CategoryDescription"));
categoryList.add(category);
/* String catId = finalObject.getString("CategoryID");
String catCompanyId = finalObject.getString("CategoryCompanyID");
String catName = finalObject.getString("CategoryName");
String catLogo = finalObject.getString("CategoryLogo");
String catIsActive =finalObject.getString("CategoryIsActive");
finalBufferedData.append("" + i + catId + "-" + catCompanyId + "-" + catName + "\n");
*/
}
Toast.makeText(getContext(), "setAdapter before", Toast.LENGTH_SHORT).show();
CateoryAdapter adapter = new CateoryAdapter(getActivity(), R.layout.custom_layout, categoryList);
Toast.makeText(getContext(), "setAdapter before", Toast.LENGTH_SHORT).show();
lvCategory.setAdapter(adapter);
Toast.makeText(getContext(), "after setAdapter", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getContext(), "staus code 0", Toast.LENGTH_SHORT).show();
}
//responsetextview.setText(finalBufferedData.toString());
// String site = response.getString("site"),
// network = response.getString("network");
//System.out.println("Site: " + site + "\nNetwork: " + network);
//Toast.makeText(getContext(), "getListData is executing", Toast.LENGTH_SHORT).show();
//responsetextview.setText(def);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(getContext()).add(jsonRequest);
}
what should i do so that the focus of the listview doesnot come back to the top of listview and it should remain where it was.
please help.
Because you create a new adapter and set it to the list.
Instead of:
CateoryAdapter adapter = new CateoryAdapter(getActivity(), R.layout.custom_layout, categoryList);
lvCategory.setAdapter(adapter);
Just add the new data to your adapter (the old one, don't create a new adapter), then call adapter.notifyDataSetChanged(); to refresh the ListView.

Categories

Resources