Listview not displaying response from retrofit api call - android

I made a retrofit call in android and got a list response objects back but for some reason, they are not getting displayed in the listview and the application is not crashing either.
public class MainActivity extends AppCompatActivity {
private OpenNotifyService mService;
ListView listView ;
List<Response> arrayList = new ArrayList<Response>();
ArrayAdapter<Response> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mService = ApiUtils.getOpenNotifyService();
// Get ListView object from xml
listView = findViewById(R.id.myListView);
adapter = new ArrayAdapter<Response>(this,android.R.layout.simple_list_item_1, android.R.id.text1, arrayList);
loadAnswers();
}
public void loadAnswers() {
mService.getTimes(12,10).enqueue(new Callback<InternationalSpaceStationPassTimes>() {
#Override
public void onResponse(Call<InternationalSpaceStationPassTimes> call, retrofit2.Response<InternationalSpaceStationPassTimes> response) {
Log.e("Request URL", call.request().url().toString());
if (response.isSuccessful()) {
arrayList= response.body().getResponse();
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
Log.d("MainActivity", "posts loaded from API");
} else {
int statusCode = response.code();
// handle request errors depending on status code
}
}
#Override
public void onFailure(Call<InternationalSpaceStationPassTimes> call, Throwable t) {
Log.d("MainActivity", "error loading from API");
}
});
}
Please help me..

Your list is initialized when your Activity instance is constructed:
List<Response> arrayList = new ArrayList<Response>();
During onCreate(), your adapter is constructed:
adapter = new ArrayAdapter<Response>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1,
arrayList);
Inside your loadAnswers() callback, your list is reinitialized:
arrayList= response.body().getResponse();
Finally, you attach the adapter to the listview:
listView.setAdapter(adapter);
Your problem is that your callback assigns a different List instance to your arrayList variable. Since your adapter was already created at this point, this means that the list inside of adapter is different from the list pointed to by arrayList. So nothing will appear.
You can solve this a couple of different ways. Probably the easiest would be to change your loadAnswers() callback to do this instead:
arrayList.clear();
arrayList.addAll(response.body().getResponse());
adapter.notifyDataSetChanged();

Related

Firebase data retrieval returns an empty screen

I am trying to retrieve data from firebase to a listview...However this code returns a blank screen .My database has got 3 children with for data fields each.
All i see is an empty screen.
I have no idea on how to solve this anyone please:The code is here
public class Business extends AppCompatActivity {
private ListView business;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
}
public ArrayList<String> arr;
public ArrayAdapter adapter;
#Override
protected void onStart() {
super.onStart();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
arr = new ArrayList<>();
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
map2list((Map) dataSnapshot.getValue());
//formats the datasnapshot entries to strings
adapter.notifyDataSetChanged();
//makes the ListView realtime
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
System.out.println(databaseError.toException());
// ...
}
};
mDatabase.addValueEventListener((com.google.firebase.database.ValueEventListener) listener);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, arr);
ListView listView = (ListView) findViewById(R.id.business);
listView.setAdapter(adapter);
}
public void map2list(Map<String,Long> map){
arr.clear();
for (Map.Entry<String, Long> entry : map.entrySet()) {
Long key = Long.parseLong(entry.getKey());
String d = DateFormat.getDateTimeInstance().format(key);
Long value = entry.getValue();
arr.add(d + ": " + value);
}
}
}
If the whole page is blank when you set the content view, this might have happened if one of your views in your layout has a layout_height attribute of 'match parent'. This may be one of the reasons why you are not seeing anything. Another reason why you might not bee seeing anything is that listeners run on separate threads. Try rearranging your code like this.
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, arr);
ListView listView = (ListView) findViewById(R.id.business);
listView.setAdapter(adapter);
mDatabase.addValueEventListener((com.google.firebase.database.ValueEventListener) listener);
// add the listner after setting the adapter

Populate spinner based on selection in other spinner

I am trying to get data from server into spinner, my json object is
{"result":{"AndhrPradesh":["Jayamahal","ABC","JP nagar"],"Mumbai":["XYZ","PQR"],"Pune":["123","Hi"]}}
I am able to get the values AndhraPradesh,Mumbai and Pune in one spinner. now my problem is after selecting city i want to display corresponding data in that city.
for example, if select Mumbai from one spinner i want to display XYZ,PQR in another spinner, Please help me.
First of all parse the json data like
JSONObject jsonObject = response.getJSONObject("data");
JSONArray cityName= jsonObject.getJSONArray("AndhrPradesh")
for(i=0;i<cityName.length();i++){
//your inner string of the Array
}
Then
citynameSpinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//here set the values to another spinner
}
});
Please use this code snippet
public class SpinnerFilterActivity extends AppCompatActivity {
private ArrayAdapter<String> mArrayAdapter;
private Spinner mMainSPN;
private ArrayList<String> mSpinnerArray;
private Map<String,ArrayList<String>> innterDataMap;
private Spinner mInnerSPN;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinnerArray = new ArrayList<String>();
innterDataMap = new HashMap<String, ArrayList<String>>();
mMainSPN = (Spinner) findViewById(R.id.spn_main);
mInnerSPN = (Spinner) findViewById(R.id.spn_inner);
mMainSPN.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String key = mSpinnerArray.get(position);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SpinnerFilterActivity.this,android.R.layout.simple_spinner_item,innterDataMap.get(key));
mInnerSPN.setAdapter(arrayAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
parseJson();
}
private void parseJson() {
String s= "{\"result\":{\"AndhrPradesh\":[\"Jayamahal\",\"ABC\",\"JP nagar\"],\"Mumbai\":[\"XYZ\",\"PQR\"],\"Pune\":[\"123\",\"Hi\"]}}\n";
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject obj= jsonObject.getJSONObject("result");
Iterator<String> stringIterator = obj.keys();
while (stringIterator.hasNext()){
String key = stringIterator.next();
mSpinnerArray.add(key);
JSONArray jsonArray = obj.getJSONArray(key);
ArrayList<String> innerList = new ArrayList<>();
for (int i=0;i<jsonArray.length();i++){
innerList.add(String.valueOf(jsonArray.get(i)));
}
innterDataMap.put(key,innerList);
}
populateDataInSpinner();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void populateDataInSpinner() {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,mSpinnerArray);
mMainSPN.setAdapter(arrayAdapter);
}
}
In this code I have kept a data in 2 fields one i mSpinnerArray to display the aster list and other is map in which inner list is kept on behalf of the key as parent value. Whenever onOptionItemSelected method gets called I fetch the list of inner data from map on behalf of the seleted item from the master list as it is working as a key in innerMap data. I hope I am clear. Let me know if there is any problem.

listView item click event not firing

I am having an issue with using a listview that when I click it nothing is happening. I would like for it when I click the listview item to make a toast so I know it is being clicked. I have been trying/researching for a while and nothing. Would anybody mind taking a look to see if I am missing something I just am overlooking? Many thanks in advance!
Here is my class:
public class MyCar extends Activity {
/**
* Called when the activity is first created.
*/
public ListView mylistView;
String carInfo;
private ArrayAdapter<String> mylistAdapter;
ArrayList<String> arrayListCar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mycar);
mylistView = (ListView) findViewById(R.id.listView);
arrayListCar = new ArrayList<String>();
//Just had to remove setting this adapter 2 times. Took out line below to fix.
mylistView.setAdapter(mylistAdapter);
mylistView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
carInfo = trySomethin();
fillList();
}
public void fillList() {
String make = "";
String model = "";
String[] pieces = carInfo.split("\"");
make = pieces[3];
model = pieces[7];
ArrayList<String> carList = new ArrayList<String>();
carList.add(make + " " + model);
// Create ArrayAdapter using the car list.
mylistAdapter = new ArrayAdapter<String>(MyCar.this, android.R.layout.simple_list_item_single_choice, carList);
mylistView.setAdapter(mylistAdapter);
mylistAdapter.notifyDataSetChanged();
}
}
if you have any elements on listview item change this for them
android:focusable="false"
and if you are changing any elements visibility on runtime you have to handle focus programatically each time you change its visibility.
Try this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});

setListAdapter not working for fragment? any alternatives

protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), inboxList,
R.layout.inbox_list_item, new String[] { TAG_LINK, TAG_SUBJECT },
new int[] { R.id.link, R.id.subject });
// updating listview
lv.setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You clicked on feed "+position, Toast.LENGTH_LONG).show();
}
});
}
});
}
Im trying to get a list view in a fragment activity.
This list view is a parsed from JSON objects.
This code runs in a fragment. However, setlistadapter gives an error. Any alternatives for setlistadapter and how to implement it.
Thank you.
Use the Custom adapter Like this:
Listview list = (Listview)findviewbyId(R.id.list);
SearchListAdapter adapter = new SearchListAdapter(this,
getActivity(), rowItems(your data to inflate in adapter));
lis.setAdapter(adapter);

How To Delete all items In ListView using ArrayAdapter in Android

I'm developing a Listview dynamically filled by a function that returns an ArrayAdapter which recieves a String parameter. This string parameter is the selected item of another dynamically filled Spinner.
When the function returns an ArrayAdapter with a number of items > 0, the Listview is sucessfully refreshed with the new items, but when the function returns 0 items on the ArrayAdapter, the listview doesn't clear the previous items. Here's the code I'm working on:
ManifiestoSpinner = (Spinner) findViewById(R.id.spnManifiesto);
FacturasListview = (ListView) findViewById(R.id.lvwFacturas);
ManifiestoSpinner = (Spinner)
ManifiestoSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String EstadoID = EstadoSpinner.getSelectedItem().toString();
ArrayList<String> ListManifiestos = (ArrayList<String>)Factura.GetManifiestosByEstado(EstadoID);
ActualizarManifiestSpinner(manifiesto);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
private void ActualizarManifiestSpinner (ArrayList<String> manifiesto)
{
String[] datos = new String[manifiesto.size()];
ArrayAdapter<String> AdapterManifiesto = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_spinner_dropdown_item, manifiesto.toArray(datos));
ManifiestoSpinner.setAdapter(AdapterManifiesto);
}
ManifiestoSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String Manifiesto = ManifiestoSpinner.getSelectedItem().toString();
String Estado = EstadoSpinner.getSelectedItem().toString();
fillData(Estado, Manifiesto);
return;
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
private void fillData(String EstadoID, String ManifiestoID) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) FacturasListview.getAdapter();
if(adapter!= null)
{
adapter.clear();
FacturasListview.setAdapter(adapter);
FacturasListview.invalidateViews();
}
List<String> from = Factura.GetListClientesByEstadoManifiesto(EstadoID, ManifiestoID);
adapter = new ArrayAdapter<String>(this,R.layout.factura_row, R.id.text1 ,from);
FacturasListview.setAdapter(adapter);
}
When the List called from has from.size() = 0, the items previously show on the Listview are not cleared.
Thanks Nammari. I followed your recommendation but the FacturasListview doesn't have a method called notifyDatasetChanged(), the adapter does, so i got this code:
ArrayAdapter<String> adapter = (ArrayAdapter<String>) mFacturasListview.getAdapter();
if(adapter!= null)
{
adapter.clear();
adapter.notifyDataSetChanged();
}
Still the Listview won't refresh the items. I'm looking for a method that will clear all the items of a ListView that recieves an ArrayAdapter. I'm uploading two pictures to show what I'm working on.
"Imagen 1"
In this case, the first spinner has a selecteditem().toString() = "POR RECIBIR", and based on that parameter, the second spinner is dynamically filled with the codes of all the documents having (document.State = "POR RECIBIR"). After the second spinner is filled, a third method called "fillData" fills the ListView with all the Customer's name included on the document. This is the code:
private void fillData(String EstadoID, String ManifiestoID) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) mFacturasListview.getAdapter();
if(adapter!= null)
{
adapter.clear();
adapter.notifyDataSetChanged();
}
List<String> from = Factura.GetListClientesByEstadoManifiesto(EstadoID, ManifiestoID);
adapter = new ArrayAdapter<String>(this,R.layout.factura_row, R.id.text1 ,from);
FacturasListview.setAdapter(adapter);
}
The problem occurs when the first spinner has a selecteditem().toString() = "POR ENTREGAR", and based on that parameter, we find 0 documents having (document.State = "POR ENTREGAR"). Here, the third method called "fillData" should clear all ListView items, but it doesn't. This is the image:
"Imagen 2"
In your fillData method
if(adapter!= null)
{
adapter.clear();
FacturasListview.setAdapter(adapter);// !!!!!!!
FacturasListview.invalidateViews();
}
after calling adapter.clear(); setting the adapter of the ListView won't change anything
just call FacturasListview.notifyDatasetChanged();
like this
if(adapter!= null)
{
adapter.clear();
FacturasListview.notifyDatasetChanged();
}
this should clear all views in the list
in case you want to change the adapter of ListView i would make a custom array adapter with a method that takes the List and change the previous reference of the List in the adapter and after that call notifyDatasetChanged();
like this
class MyAdpater {
List<String> list;
.....
.....
public void setAdpaterList(List<String>list){
this.list= list;
}
}
then after calling this method call notifyDatasetChange() on your adapter

Categories

Resources