Android Restful API retrofit fetching data on Create method but not display - java

Here is complete code
(In first activity two values are taken from spinner and through a function data sent to second activity)
First Activity:
public class FindBloodActivity extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
TextView t;
Spinner spbgid;
Spinner spcityid;
ProgressBar pro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_blood);
t = (TextView) findViewById(R.id.tv);
pro=(ProgressBar) findViewById(R.id.progressBar2);
pro.setVisibility(View.INVISIBLE);
spbgid=(Spinner) findViewById(R.id.spinnerBG);
spcityid=(Spinner) findViewById(R.id.spinnerLocation);
t.setVisibility(View.INVISIBLE);
}
public void SearchOn(View v) {
String BGId = Integer.toString(spbgid.getSelectedItemPosition()+1);
String CityId =Integer.toString(spcityid.getSelectedItemPosition()+1);
Intent intent=new Intent(getApplicationContext(),SearchResult2.class);
intent.putExtra("bid",BGId);
intent.putExtra("cid",CityId);
startActivity(intent);
}
}
Second Activity: In second activity on tt.append(string.toString()); working fine, but when i add below code than application terminated if i try to debug than also application terminate.
public class SearchResult2 extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
Spinner sp;
TextView t;
TextView tt;
public int totalUsersCount = 0;
String[] allUserNames;
String[] allUserContacts;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result2);
tt=(TextView)findViewById(R.id.tvTest);
tt.setVisibility(View.INVISIBLE);
Bundle extras = getIntent().getExtras();
String BGId = extras.getString("bid");
String CityId = extras.getString("cid");
tt.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git = restAdapter.create(gitapi.class);
git.SearchUsers(BGId, CityId, new Callback<String>() {
#Override
public void success(String string, Response response) {
tt.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
tt.setText("No User Found");
}
});
String bigArray = tt.getText().toString();
listView = (ListView)findViewById(R.id.lvUsers);
bigArray = bigArray.substring(0, bigArray.length() - 1);
totalUsersCount = bigArray.split(",").length;
listView.clearTextFilter();
if (totalUsersCount > 0)
{
String[] allUsers = new String[totalUsersCount];
allUsers = bigArray.split(",");
allUserNames = new String[totalUsersCount];
allUserContacts = new String[totalUsersCount];
String[] temp = new String[3];
for (int i = 0; i < totalUsersCount; i++) {
temp = allUsers[i].split("-");
allUserNames[i] = temp[1];
allUserContacts[i] = temp[2];
}
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
}
}
}
This is log
02-08 12:40:51.433 9970-10008/com.example.abdulqadir.bd I/OpenGLRenderer: Initialized EGL, version 1.4
02-08 12:40:51.457 9970-10008/com.example.abdulqadir.bd W/linker: /vendor/lib64/libhwuibp.so: unused DT entry: type 0xf arg 0xe3a
02-08 12:40:51.458 9970-9970/com.example.abdulqadir.bd W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
02-08 12:40:51.548 9970-10008/com.example.abdulqadir.bd E/hwaps: APS: SSR : The platform cannot support SSR !: 0x0,0x0,8
This code below is working fine for me but when i changed this to above than getting errors, here is code please check
public class FindBloodActivity extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
TextView t;
Spinner spbgid;
Spinner spcityid;
ProgressBar pro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_blood);
t = (TextView) findViewById(R.id.tv);
pro=(ProgressBar) findViewById(R.id.progressBar2);
pro.setVisibility(View.INVISIBLE);
spbgid=(Spinner) findViewById(R.id.spinnerBG);
spcityid=(Spinner) findViewById(R.id.spinnerLocation);
t.setVisibility(View.INVISIBLE);
}
public void SearchOn(View v) {
String BGId = Integer.toString(spbgid.getSelectedItemPosition()+1);
String CityId =Integer.toString(spcityid.getSelectedItemPosition()+1);
SearchAllUsers(BGId.toString(), CityId.toString());
}
public void SearchAllUsers(String BGId,String CityId) {
t.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git= restAdapter.create(gitapi.class);
git.SearchUsers(BGId,CityId,new Callback<String>() {
#Override
public void success(String string, Response response) {
t.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
t.setText("No User Found");
}
});
}
public void Search(View v){
try {
Thread.sleep(9000);
Intent intent=new Intent(getApplicationContext(),SearchResult.class);
intent.putExtra("users",t.getText().toString());
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Second Activity:
public class SearchResult2 extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
Spinner sp;
TextView t;
TextView tt;
public int totalUsersCount = 0;
String[] allUserNames;
String[] allUserContacts;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result2);
tt=(TextView)findViewById(R.id.tvTest);
tt.setVisibility(View.INVISIBLE);
Bundle extras = getIntent().getExtras();
String BGId = extras.getString("bid");
String CityId = extras.getString("cid");
tt.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git = restAdapter.create(gitapi.class);
git.SearchUsers(BGId, CityId, new Callback<String>() {
#Override
public void success(String string, Response response) {
tt.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
tt.setText("No User Found");
}
});
String bigArray = tt.getText().toString();
listView = (ListView)findViewById(R.id.lvUsers);
bigArray = bigArray.substring(0, bigArray.length() - 1);
totalUsersCount = bigArray.split(",").length;
listView.clearTextFilter();
if (totalUsersCount > 0)
{
String[] allUsers = new String[totalUsersCount];
allUsers = bigArray.split(",");
allUserNames = new String[totalUsersCount];
allUserContacts = new String[totalUsersCount];
String[] temp = new String[3];
for (int i = 0; i < totalUsersCount; i++) {
temp = allUsers[i].split("-");
allUserNames[i] = temp[1];
allUserContacts[i] = temp[2];
}
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
}
}

Here are the things you can try, use this code in onCreate()
listView = (ListView)findViewById(R.id.lvUsers);
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
and where you were using the above code before replace it with i.e of inside of if condition
itemsAdapter.notifyDatasetChanged();
Hope this helps

Why not do your REST call from the onCreate() method?
Also component.setVisibility(View.INVISIBLE); retains space in the overall layout. You could use 'GONE' instead and see if that helps or hurts.
And try have your URL and other components in different methods or classes. This can help a WHOLE LOT to keep the code clean and easy to find errors.
With all this said, after using breakpoints and running in debug mode which line is the error?

Related

notifyDataSetChanged() blanks out recyclerview

I have an issue where notifyDataSetChanged() in a response call will blank out the recyclerview but if the Adapter is initiated manually with a onClick, the recyclerview works. I have tested that the List has the items inside before calling notifyDataSetChanged() so i'm not sure what's wrong here.
[Main Activity] This works but i have to manually click the bnQuery.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = API_client.getClient().create(APIInterface.class);
etCoin = (EditText) findViewById(R.id.etCoin);
bnQuery = (Button) findViewById(R.id.bnQuery);
rcvMain = findViewById(R.id.rcvMain);
getCoinData("2");
//initRCV_Main();
bnQuery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getCoinData("2");
initRCV_Main();
}
});
}
private void initRCV_Main() {
rcvMainAdp = new rcvMainAdapter(cList);
rcvMain.setAdapter(rcvMainAdp);
rcvMain.setLayoutManager(new LinearLayoutManager(this));
}
private void getCoinData(String coinLimit){
Call<cInfoPack> call = apiInterface.doGetCoinData(coinLimit);
call.enqueue(new Callback<cInfoPack>() {
#Override
public void onResponse(Call<cInfoPack> call, Response<cInfoPack> response) {
cInfoPack list = response.body();
List<cData> listSorter = new ArrayList<>();
listSorter.addAll(list.getData());
Collections.sort(listSorter, new SortbyVolChg());
cList.clear();
cList = listSorter;
System.out.println("list " + list.getData().get(0).getQuote());
System.out.println("listSorter " + listSorter.get(0).getQuote());
System.out.println("cList " + cList.get(0).getQuote());
//rcvMainAdp.notifyDataSetChanged();
}
#Override
public void onFailure(Call<cInfoPack> call, Throwable t) {
Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
Log.d("XXXX", t.getLocalizedMessage());
call.cancel();
}
});
}
[Main Activity] If i initiate the recyclerview during onCreate and use the notifyDataSetChanged() during getCoinData, I get a blank recycleview. system.out shows that the lists all contain information in them.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = API_client.getClient().create(APIInterface.class);
etCoin = (EditText) findViewById(R.id.etCoin);
bnQuery = (Button) findViewById(R.id.bnQuery);
rcvMain = findViewById(R.id.rcvMain);
getCoinData("2");
initRCV_Main();
bnQuery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getCoinData("2");
//initRCV_Main();
}
});
}
private void initRCV_Main() {
rcvMainAdp = new rcvMainAdapter(cList);
rcvMain.setAdapter(rcvMainAdp);
rcvMain.setLayoutManager(new LinearLayoutManager(this));
}
private void getCoinData(String coinLimit){
Call<cInfoPack> call = apiInterface.doGetCoinData(coinLimit);
call.enqueue(new Callback<cInfoPack>() {
#Override
public void onResponse(Call<cInfoPack> call, Response<cInfoPack> response) {
cInfoPack list = response.body();
List<cData> listSorter = new ArrayList<>();
listSorter.addAll(list.getData());
Collections.sort(listSorter, new SortbyVolChg());
cList.clear();
cList = listSorter;
System.out.println("list " + list.getData().get(0).getQuote());
System.out.println("listSorter " + listSorter.get(0).getQuote());
System.out.println("cList " + cList.get(0).getQuote());
rcvMainAdp.notifyDataSetChanged();
}
#Override
public void onFailure(Call<cInfoPack> call, Throwable t) {
Toast.makeText(MainActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
Log.d("XXXX", t.getLocalizedMessage());
call.cancel();
}
});
}
[Adapter]
public class rcvMainAdapter extends RecyclerView.Adapter<rcvMainAdapter.ViewHolder> {
private List<cData> idxCoin;
//ItemClickListener itemClickListener;
rcvMainAdapter(List<cData> data) {this.idxCoin = data;}
#NonNull
#NotNull
#Override
public ViewHolder onCreateViewHolder(#NonNull #NotNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.rcv_main,parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull #NotNull ViewHolder holder, int position) {
cData cdata = idxCoin.get(position);
TextView tvSym = holder.tvSymbol;
tvSym.setText(cdata.getSymbol());
TextView tvQuo = holder.tvQuote;
BigDecimal tvQuote_BD = new BigDecimal(cdata.getQuote().getuSD().getPrice().toString());
tvQuote_BD.setScale(6, RoundingMode.DOWN);
tvQuo.setText(tvQuote_BD.toString());
TextView tvV24 = holder.tvVolume24;
BigDecimal tvVolume24_BD = new BigDecimal(cdata.getQuote().getuSD().getVolume24h().toString());
BigInteger tvVolume24_BI = tvVolume24_BD.toBigInteger();
tvV24.setText(tvVolume24_BI.toString());
}
#Override
public int getItemCount() {
return idxCoin.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView tvSymbol, tvQuote, tvVolume24;
public ViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
tvSymbol = itemView.findViewById(R.id.tvSymbol);
tvQuote = itemView.findViewById(R.id.tvQuote);
tvVolume24 = itemView.findViewById(R.id.tvVolume24);
//itemView.setOnClickListener(this);
}
}
/*
public interface ItemClickListener{
void onItemClick(View view, int position);
}
*/
}
PS: apologies for the rubbish coding as this is self taught and modifying some codes found online.
Remove this in response.
cList.clear();
Add This line in response
rcvMainAdp.setdata(listSorter);
In rcvMainAdp Adapter, Create a Method setdata()
public void setdata(ArrayList<cData> data) {
this.idxCoin = data;
notifyDataSetChanged();
}
Problem most likely is that when you call initRCV_Main() You set the adapter to the list as in rcvMainAdp = new rcvMainAdapter(cList); And when list is changed and you set it to adapter it functions.
But when you call getCoinData() and rcvMainAdp.notifyDataSetChanged(); at the end you never set the changed list to the adapter until you click initRCV_Main() again.
So maybe the fix is calling rcvMainAdp = new rcvMainAdapter(cList) and then
rcvMainAdp.notifyDataSetChanged();

How to get total by adding all the recycler views rows

I have recycler view in my activity and below there is a total cost field which shows the total value comes after adding the values from each row. As shown in the screen below:
In a recycler view, there is a spinner that shows quantity on selecting a value from spinner it will be multiplied by the MRP like this every same row have some values. I want to add this value and want to show it in the Lower left corner.
So far I am sending MRP value from adapter class to activity using LocalBroadcatManager class.
But every time I selecting data from another row it does not add cost with the previous value
but it replaces the older value.
Below is my code:
ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
private Context context;
private List<ProductsModel> productList;
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
if (!item.equals("Select qty")) {
int qty = Integer.parseInt(item);
int cost = Integer.parseInt(model.getMrp());
int val = cost * qty;
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}
SelectPack.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_pack);
fAuth = FirebaseAuth.getInstance();
ActionBar ab = getSupportActionBar();
assert ab!= null;
ab.setTitle("Select Pack");
ab.setDisplayHomeAsUpEnabled(true);
marketSpinner = findViewById(R.id.marketSpinner);
progress = findViewById(R.id.progress);
products = findViewById(R.id.products);
totalCost = findViewById(R.id.totalCost);
products.setHasFixedSize(true);
products.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<>();
List<String> categories = new ArrayList<String>();
categories.add("Select market");
categories.add("Crown");
categories.add("Long Book A4");
categories.add("Long Book");
categories.add("Crown Junior");
categories.add("Physics");
categories.add("Chemistry");
categories.add("Biology");
categories.add("Universal");
categories.add("Sketch Book");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
marketSpinner.setAdapter(dataAdapter);
marketSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if(item.equals("Select market")){
progress.setVisibility(View.INVISIBLE);
}
else{
getData(item);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
LocalBroadcastManager.getInstance(SelectPack.this).registerReceiver(message,new IntentFilter("msg"));
}
private void getData(String item){
progress.setVisibility(View.VISIBLE);
products.setVisibility(View.INVISIBLE);
productList.clear();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.build();
RequestBody formBody = new FormBody.Builder()
.add("name",item)
.build();
Request request = new Request.Builder().post(formBody).url(URL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(#NotNull Call call, #NotNull final Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(response.body().string());
if(jsonArray.length() > 0){
products.setVisibility(View.VISIBLE);
progress.setVisibility(View.INVISIBLE);
}
for(int i=0;i<jsonArray.length();i++){
progress.setVisibility(View.INVISIBLE);
JSONObject object = jsonArray.getJSONObject(i);
String str1 = object.getString("market");
String str2 = object.getString("product_no");
String str3 = object.getString("page");
String str4 = object.getString("mrp");
String str5 = object.getString("inner_pack");
String str6 = object.getString("outer_pack");
Log.d("prod",str2);
ProductsModel model = new ProductsModel(str1,str2,str3,str4,str5,str6);
productList.add(model);
}
ProductAdapter adapter = new ProductAdapter(getApplicationContext(),productList);
products.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onFailure(#NotNull Call call, #NotNull final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.setVisibility(View.INVISIBLE);
products.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
public BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String nam = intent.getStringExtra("cost");
if(nam != null){
int val = Integer.parseInt(nam);
totalCost.setText("Total: "+val+".00");
}
}
};
Someone, please let me know what I am doing wrong or how should I implement it correctly. Any help would be appreciated.
THANKS
why you are using local broadcasts to communicate with activity. Instead, use interface to communicate it will be easy to use.
I found the problem when the item is getting selected you are passing the only current value not all the selected value that's why it is showing the latest value instead of all the value.
You should pass all the selected values from the list, let's say If I select one value, keep that in the separate list or you can manage with a flag in the current list object and when user selects any item then loop through that list and add all the price and pass it to activity.
Add one field in ProductsModel called Qty
Here is my updated adapter class I have added a comment as well please try this Hope it helps
public class ProductAdapter extends RecyclerView.Adapter {
private Context context;
private List<ProductsModel> productList;
// add this list
private List<ProductsModel> selectedProductList = new ArrayList();
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
// add this line
adapterView.getItemAtPosition(i);
if (!item.equals("Select qty")) {
// add this line
model.setQty(Integer.parseInt(item));
selectedProductList.add(model);
}
int val = 0;
for(int j = 0; j < selectedProductList.size(); j++){
ProductsModel model = selectedProductList.get(i);
int mrp = model.getMrp();
int qty = model.getQty();
val = val + (mrp * qty);
}
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}

Missing data depending on the number of tabs

I want to create multiple tabs depending on number of items retained from API. I have successfully created tabs, and swiping over is working fine, but the issue is that for instance, let's say I have 3 tabs. When they are all created, first and second tabs are empty, and the third has data, when I swipe back to 1, I see the data loaded too, but never on the second tab. When the tabs are 2, neither show data. Here is my code:
Activity
public class MenuActivity extends AppCompatActivity {
private ViewPager tabsPager;
private Toolbar toolbar;
private ImageView toolbarImageView;
private TextView subTitleView, titleView, priceCounterView, itemsCounterView;
private RatingBar ratingBar;
private TabLayout tabLayout;
private LinearLayout cartButton;
private AVLoadingIndicatorView avi;
private MenuPagerAdapter tabsAdapter;
public List<MenuType> menuTypes = new ArrayList<>();
public List<MenuItem> menuItems = new ArrayList<>();
private Restaurant restaurant;
private Context context;
private CollapsingToolbarLayout collapsingToolbarLayout;
private AppBarLayout appBarLayout;
private int i = -1;
public List<Fragment> fragments = new ArrayList<>();
private int cartCount = 0;
private int priceCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
context = this;
tabsPager = (ViewPager) findViewById(R.id.tabs_pager);
toolbar = (Toolbar) findViewById(R.id.toolbar);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
avi = (AVLoadingIndicatorView) findViewById(R.id.avi);
titleView = (TextView) findViewById(R.id.titleView);
subTitleView = (TextView) findViewById(R.id.subTitle);
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
toolbarImageView = (ImageView) findViewById(R.id.restoIcon_toolbar);
appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
priceCounterView = (TextView) findViewById(R.id.items_price_counter);
itemsCounterView = (TextView) findViewById(R.id.items_counter);
cartButton = (LinearLayout) findViewById(R.id.view_order_button);
if (cartCount == 0 && priceCount == 0){
cartButton.setVisibility(View.GONE);
}
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
tabsPager.setCurrentItem(0);
restaurant = (Restaurant) getIntent().getSerializableExtra("restaurant");
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.totalTransparent));
getSupportActionBar().setTitle(restaurant.getName());
titleView.setText(restaurant.getName());
subTitleView.setText(restaurant.getSlogan());
ratingBar.setRating(Float.parseFloat(restaurant.getRating()));
Picasso.with(context)
.load(restaurant.getImageURL())
.placeholder(R.drawable.restaurant_placeholder)
.into(toolbarImageView);
loadMenuTypes();
}
//LOAD MENU TYPES
public void loadMenuTypes(){
RequestQueue queue = Volley.newRequestQueue(this);
String url = getResources().getString(R.string.api) + "get-menu-types";
final StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("menu_types");
for (int i = 0; i < array.length(); i++){
JSONObject restoMainMenu = array.getJSONObject(i);
if (restoMainMenu.getBoolean("hasData")) {
MenuType menuType = new MenuType();
menuType.setMenuIcon(restoMainMenu.getString("icon"));
menuType.setRestaurant(restaurant);
menuType.setRmenu(restoMainMenu.getString("title"));
menuType.setMenuId(restoMainMenu.getString("id"));
menuTypes.add(menuType);
}
}
} catch (JSONException e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
loadMenuItems();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
menuTypes.clear();
menuItems.clear();
loadMenuTypes();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("UID", restaurant.getId());
return params;
}
};
queue.add(postRequest);
}
//LOAD MENUS
public void loadAllMenu(final MenuType mMenuType){
RequestQueue queue = Volley.newRequestQueue(this);
String url = getResources().getString(R.string.api) + "get-all-menu";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("detailed_menus");
List<MenuItem> menuItems1 = new ArrayList<>();
for (int i = 0; i< array.length(); i++){
JSONObject restoDetailMenu = array.getJSONObject(i);
MenuItem item = new MenuItem(
restaurant.getId(),
restoDetailMenu.getString("Name"),
restoDetailMenu.getString("id"),
restoDetailMenu.getString("Price"),
restoDetailMenu.getString("Description"),
restoDetailMenu.getString("AvailableIn"),
restoDetailMenu.getString("Icon")
);
menuItems.add(item);
menuItems1.add(item);
}
mMenuType.setMenuItems(menuItems1);
}
catch (JSONException e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
loadAllMenu(menuTypes.get(i));
Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("MenuTypeId", mMenuType.getMenuId());
params.put("restId", mMenuType.getRestaurant().getId());
return params;
}
};
queue.add(postRequest);
}
//TRIGER ALL MENU LOADER
public void loadMenuItems(){
for (int j = 0; j < menuTypes.size(); j++) {
i = j;
loadAllMenu(menuTypes.get(j));
}
avi.setVisibility(View.GONE);
setUpTabs();
}
public void setUpTabs(){
for (int j = 0; j < menuTypes.size(); j++) {
tabLayout.addTab(tabLayout.newTab().setText(menuTypes.get(j).getRmenu()));
MenuFragment fragment = new MenuFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("data", menuTypes.get(j));
fragment.setArguments(bundle);
fragments.add(MenuFragment.newInstance(menuTypes.get(j)));
}
tabsAdapter = new MenuPagerAdapter(getSupportFragmentManager(), menuTypes);
tabsAdapter.notifyDataSetChanged();
tabsPager.setAdapter(tabsAdapter);
tabLayout.setupWithViewPager(tabsPager);
tabsPager.setAdapter(tabsAdapter);
}
public void addedToCart(int price){
priceCount = priceCount + price;
cartCount = cartCount + 1;
if (cartCount > 0 && priceCount > 0){
if (cartCount == 1){
itemsCounterView.setText( String.valueOf(cartCount) + " item");
} else {
itemsCounterView.setText( String.valueOf(cartCount) + " items");
}
priceCounterView.setText(String.valueOf(priceCount) + " RWF");
cartButton.setVisibility(View.VISIBLE);
} else {
cartButton.setVisibility(View.GONE);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
PagerAdapter
public class MenuPagerAdapter extends FragmentStatePagerAdapter {
private List<MenuType> menuTypes;
public MenuPagerAdapter(FragmentManager fm, List<MenuType> menuTypes) {
super(fm);
this.menuTypes = menuTypes;
}
#Override
public Fragment getItem(int position) {
return MenuFragment.newInstance(menuTypes.get(position));
}
#Override
public int getCount() {
return menuTypes.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return menuTypes.get(position).getRmenu();
}
}
Fragment
public class MenuFragment extends Fragment {
#BindView(R.id.menuRecyclerView) RecyclerView menuRecyclerView;
#BindView(R.id.avi) AVLoadingIndicatorView avi;
private MenuType menuType;
private Bundle args;
private MenuAdapter adapter;
private Context context;
private int position;
public MenuFragment() {
// Required empty public constructor
}
public static MenuFragment newInstance(MenuType mMenuType){
MenuFragment fragment = new MenuFragment();
Bundle args = new Bundle();
args.putSerializable("data", mMenuType);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
ButterKnife.bind(this, view);
context = container.getContext();
menuRecyclerView.setHasFixedSize(true);
menuRecyclerView.setLayoutManager(new LinearLayoutManager(context));
adapter = new MenuAdapter(menuType.getMenuItems(), context);
menuRecyclerView.setAdapter(adapter);
avi.setVisibility(View.GONE);
setData();
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
args = getArguments();
menuType = (MenuType) args.getSerializable("data");
}
public MenuType getMenuType() {
return menuType;
}
public void setMenuType(MenuType menuType) {
this.menuType = menuType;
}
public void setData(){
adapter = new MenuAdapter(menuType.getMenuItems(), getActivity());
menuRecyclerView.setAdapter(adapter);
avi.setVisibility(View.GONE);
}
}
As it is seen, I'm loading MenuTypes(List) first, then for each MenuType, I load all associated items (MenuItems) List too. I, then, create Tabs with respect to the number of MenuTypes, and then create instances of the MenuFragment with respect to the number of MenuItems in the list, and the for each instance of MenuFragment, I just list MenuItems for particular MenuType in a RecyclerView(which is working fine). I tried to add a static TextView in the MenuFragment, and it was shown every time, on all tabs, but the actual data I want are not shown. I also tried a temporary solution to manually set Data I want to each created fragment from the Activity in OnPageChangeListener, but it was not directly working on the first tab until I first navigate to any other tab, which made me to opt out the strategy. Any help is much appreciated. Screenshots are also included for reference.
When tabs are 2 (Screenshot)
When tabs are 2 (Screenshot)
3 tabs, at first, the tab 1 is empty (Screenshot)
3 tabs, last tab has data (Screenshot)
3 tabs, After navigating tabs, the tab 1 also got data (Screenshot)
3 tabs, tab 2 never gets data (Screenshot)
The answer is to use the newInstance() function of the Fragment, and pass everything you want initially as arguments.

OnItemClicklistener on list adapter that populate its items from database

I have a list view that implement swipelistadapter and app controller. The list view display correctly from the database, the only thing I need is to get position of each item and assign intent activity on each. These are my codes
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
Below Class is the main activity
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.158.33.172/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) v.findViewById(R.id.list);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//String selectedFromList = (listView.getItemAtPosition(position).getString());
// String text = movieList[position];
Intent i = new Intent(getActivity(), Tab2.class);
// i.putExtra("TEXT", text);
startActivity(i);
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
Any help will be appreciated. Thanks.
Code for getting a single item:
String singleItem = getItem(position);
this is quite straight forward. here is a modification to your onItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = movieList.get(position);
Intent i = new Intent(getActivity(), Tab2.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
just note that movieList object should be the same object you pass to your adapter

Listview not updating using volley library

hi everyone i had creating a chating app and getting the users chating data in one listview.this usersdata is called using json by volley library and all these are placed in a method and this method is placed in handler and this handler is refreshed for every 5 seconds.but the listview adapter is not updating.I had struck in this nearly from 20days please anybody help me out i am not able to understand what had i done wrong
suppose listview contains 5 items and when i add an 6item this item is not updating in listview.
ChatList.java
public class Messages extends ActionBarActivity {
ListView chatview;
List<CBData> chatdata;
TextView sendbutton;
EditText msget;
String message;
ChatAdapter_Row chatAdapter;
ImageButton msg_menu, videobutton;
ImageView callbutton;
TextView name, viewprofile;
ImageView backbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_details);
chatview = (ListView) findViewById(R.id.chatview);
sendbutton = (TextView) findViewById(R.id.sendbutton);
msget = (EditText) findViewById(R.id.msget);
chatdata = new ArrayList<CBData>();
chatAdapter = new ChatAdapter_Row(Messages.this, chatdata);
chatview.setStackFromBottom(true);
chatview.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
chatview.setAdapter(chatAdapter);
sendbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = msget.getText().toString();
sendmethod();
}
});
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
chatAdapter.notifyDataSetChanged();
handler.postDelayed( this,5000 );
}
},5000 );
chatmethod();
}
private void chatmethod() {
String receiverid = getIntent().getStringExtra("ReceiverID");
String chaturl = Constant.URL + "chathome.php?sid=" + Session.getUserID(getApplicationContext()) + "&rid=" + receiverid;
Display.displaylog("ChatUrl", chaturl);
JsonObjectRequest chatobj = new JsonObjectRequest(Request.Method.GET, chaturl, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray chatarray = response.getJSONArray("chats");
for (int i = 0; i < chatarray.length(); i++) {
JSONObject chatjsonobj = chatarray.getJSONObject(i);
CBData cbData = new CBData();
cbData.setOwerid(chatjsonobj.getString("sender_id"));
cbData.setChatmsg(chatjsonobj.getString("message"));
cbData.setChatid(chatjsonobj.getString("chat_id"));
cbData.setChatsendername(chatjsonobj.getString("sender_first_name"));
cbData.setChattype(chatjsonobj.getString("chat_type"));
cbData.setChatsenderlastname(chatjsonobj.getString("sender_last_name"));
chatdata.add(cbData);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Display.displaylog("Chat", String.valueOf(error));
}
});
chatobj.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(chatobj);
}
}
ChatListAdapter.java
public class ChatAdapter_Row extends BaseAdapter {
Context chatcontext;
List<CBData> chatadaprow;
LayoutInflater inflater;
public ChatAdapter_Row(Context chatcontext, List<CBData> chatadaprow) {
this.chatcontext = chatcontext;
this.chatadaprow = chatadaprow;
}
#Override
public int getCount() {
return chatadaprow.size();
}
#Override
public Object getItem(int position) {
return chatadaprow.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) chatcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Chathold chathold;
if (convertView == null) {
convertView = inflater.inflate(R.layout.chat_row, parent, false);
chathold = new Chathold();
chathold.betweenname= (TextView) convertView.findViewById(R.id.betweenname);
chathold.msg= (TextView) convertView.findViewById(R.id.msg);
chathold.chatimage= (ImageView) convertView.findViewById(R.id.chatimage);
convertView.setTag(chathold);
}else {
chathold= (Chathold) convertView.getTag();
}
CBData chatdata=chatadaprow.get(position);
String cont=chatdata.getChatsendername()+" "+chatdata.getChatsenderlastname();
chathold.betweenname.setText(cont);
String chattype=chatdata.getChattype();
if (chattype.equals("text")){
chathold.msg.setText(chatdata.getChatmsg());
}else if (chattype.equals("image")){
chathold.msg.setVisibility(View.GONE);
chathold.chatimage.setVisibility(View.VISIBLE);
Glide.with(chatcontext).load(chatdata.getChatmsg()).into(chathold.chatimage);
}
return convertView;
}
static class Chathold {
TextView betweenname, msg;
ImageView chatimage;
}
}
problem I see you are calling chatMethod() only once at your activity. So please put your chatMethod() function inside in your handler and make your handler repetitive for every 5 second.
chatmethod();
handler.postDelayed( new Runnable() {
#Override
public void run() {
chatmethod();
handler.postDelayed( this,5000 );
}
},5000 );
Also you need to move your notifyDataSetChanged() to onResponse at your Volley call result. Because it will refresh your list view after succesfull Voley result.
try {
JSONArray chatarray = response.getJSONArray("chats");
for (int i = 0; i < chatarray.length(); i++) {
JSONObject chatjsonobj = chatarray.getJSONObject(i);
CBData cbData = new CBData();
cbData.setOwerid(chatjsonobj.getString("sender_id"));
cbData.setChatmsg(chatjsonobj.getString("message"));
cbData.setChatid(chatjsonobj.getString("chat_id"));
cbData.setChatsendername(chatjsonobj.getString("sender_first_name"));
cbData.setChattype(chatjsonobj.getString("chat_type"));
cbData.setChatsenderlastname(chatjsonobj.getString("sender_last_name"));
chatdata.add(cbData);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Important part
chatAdapter.notifyDataSetChanged();

Categories