List doesn't show data - android

I have strings stored (objectIDs) in my internal storage. When I want to display the list of the IDs saved it works, however when I try to get the Names from Parse.com It doesn't show up on the list.
This shows ObjectIds:
public class UserListForHistory extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list_for_history);
SharedPreferences settings = getSharedPreferences("NotificationIDs", Context.MODE_PRIVATE);
Set<String> myStrings = settings.getStringSet("myStrings", new HashSet<String>());
ListView idList;
List<String> idListData;
idListData = new ArrayList<String>();
idList = (ListView) findViewById(android.R.id.list);
for(String userIds : myStrings){
idListData.add(userIds);
}
ArrayAdapter<String> str = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, idListData);
idList.setAdapter(str);
}
However when add this to "for" It doesn't display anything in the list! But it does display all on the names in logcat. Anyone see the problem?
public class UserListForHistory extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list_for_history);
SharedPreferences settings = getSharedPreferences("NotificationIDs", Context.MODE_PRIVATE);
Set<String> myStrings = settings.getStringSet("myStrings", new HashSet<String>());
final ListView idList;
final List<String> idListData;
idListData = new ArrayList<>();
idList = (ListView) findViewById(android.R.id.list);
for(String userIds : myStrings) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.getInBackground(userIds, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
String name = parseObject.getString("fullname");
Log.d("These are the names: ", name);
idListData.add(name);
}
});
}
ArrayAdapter<String> str = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, idListData);
idList.setAdapter(str);
}

The calls inside this for loop:
for(String userIds : myStrings) {
query.getInBackground(userIds, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
String name = parseObject.getString("fullname");
Log.d("These are the names: ", name);
idListData.add(name);
}
});
}
are asynchronous, which means that idListData is still empty when your code reaches the following lines:
ArrayAdapter<String> str = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, idListData);
idList.setAdapter(str);
To fix this, you could do something like the following:
final ArrayAdapter<String> str = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, new ArrayList<>());
idList.setAdapter(str);
for(String userIds : myStrings) {
query.getInBackground(userIds, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
String name = parseObject.getString("fullname");
Log.d("These are the names: ", name);
str.add(name);
}
});
}
In this code, the adapter is associated with the list synchronously, and asynchronously-retrieved data is then added to the adapter once it is available. Your exact implementation may vary based on how often you are executing this set of queries, but the code above (not compiled, so may contain typos) should illustrate the general principle for you.

Related

I've been trying to display the content of my database however I keep getting this error "java.lang.String cannot be cast to java.util.HashMap" [duplicate]

I like to pass selected item value from ListView to another activity.I am using City class with atributes idCity and nameCity and I like to pass the value of the city that is selected to another activity
This code is throwing java.lang.ClassCastException: java.lang.String cannot be cast to java.util.HashMap
public ListView cities;
ArrayList<City> cityList=new ArrayList<City>();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cities_view);
Resources r = getResources();
String[] c = r.getStringArray(R.array.cities);
for(int i=0;i<c.length;i++)
{
cityList.add(new City(i,c[i]));
}
for(int i=0;i<c.length;i++)
{
System.out.println(cityList.get(i).idCity);
System.out.println(cityList.get(i).nameCity);
}
cities = (ListView) findViewById(R.id.listCities);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, c);
cities.setAdapter(adapter);
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), getString(R.string.exchangeOfficesFile));
if (!file.exists()) {
startService(new Intent(this, DownloadAsyncService.class));
}
try{
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (City c : cityList) {
Map<String, String> map = new HashMap<String, String>(2);
map.put("idCity", Integer.toString(c.getIdCity()));
map.put("nameCity", c.getNameCity());
data.add(map);
}
cities.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getApplicationContext(),
CitiesDetails.class);
HashMap<String,String> map=(HashMap<String, String>) parent.getItemAtPosition(position);
intent.putExtra("idCity", map.get("idCity"));
intent.putExtra("nameCity", map.get("nameCity"));
startActivity(intent);
}
});
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Maybe somebody had the same problem?
Your array adapter is a list of strings:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, c);
getItemAtPosition(int position) will return an Object that matches the type of the Adapter. So in this case it will return a string, but you are trying to cast it to a HashMap<String, String>
HashMap<String,String> map=(HashMap<String, String>) parent.getItemAtPosition(position);
Change it to:
String result = (String) parent.getItemAtPosition(position);

I need to show this data from Parser in a listview, how do I?

I need to show this data in a listview, it's relational data, I already know how to re-emerge, what I do not know is how it shows it, I'm doing it inside an activity.
final ListView listview = (ListView) findViewById(R.id.lvComentario);
final String[][] values = {new String[]{" linda", " bonita"}};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values[0].length; ++i) {
list.add(values[0][i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
comentario = (EditText) findViewById(R.id.text_comentario);
botaoSalvar = (Button) findViewById(R.id.button_salvar);
Intent i = getIntent();
obID = i.getStringExtra("imagem");
//exibirComentario();
ParseQuery<ParseObject> query = ParseQuery.getQuery("comentario");
query.whereEqualTo("parentesco", obID);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> commentList, ParseException e) {
if (e == null) {
Log.d("score", "no doctor available: ");
} else {
Log.w("Parse query", e.getMessage());
}
adapter.notifyDataSetChanged();
}
});
You need to set adapter after you receive data from parse.
final ListView listview = (ListView) findViewById(R.id.lvComentario);
ParseQuery<ParseObject> query = ParseQuery.getQuery("comentario");
query.whereEqualTo("parentesco", obID);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> commentList, ParseException e) {
if (e == null) {
Log.d("score", "no doctor available: ");
} else {
Log.w("Parse query", e.getMessage());
//Use your custom adapter according to your comment list or design
final StableArrayAdapter adapter = new StableArrayAdapter(this,android.R.layout.simple_list_item_1, commentList);
listview.setAdapter(adapter);
}
}

How to display name in spinner dynamically from server

Hi Now I'm retrieving data to spinner dynamically, but now it displaying some id's but those Id details are stored in other table, I want display those details in the spinner instead of id. And if I select particular product in spinner according that product details should display in list.
I'm using Retrofit method for retrieving data from server
package cfirst.live.com.activity;
public class Pos_outlet extends AppCompatActivity implements RestCallback,View.OnClickListener{
Spinner spinner;
ArrayList<String> products;
String numberAsString, product_name;
int i;
private int cartProductNumber = 0;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pos_outlet);
sharedPreference = new MySharedPreference(Pos_outlet.this);
GsonBuilder builder = new GsonBuilder();
gson = builder.create();
initViews();
}
private void initViews() {
row1 =(TableRow)findViewById(R.id.row1);
spinner=(Spinner)findViewById(R.id.spinner);
POSStoreID = (TextView) findViewById(R.id.POSStoreID);
POSLocationID = (TextView) findViewById(R.id.POSLocationID);
Intent intent = getIntent();
id = intent.getStringExtra("id");
index_id= intent.getStringExtra("index_id");
callStoreDetaislsAPI();
callSmbProductsAPI();
getProductAPI();
}
// **Using this api I'm setting id'd to spinner**
private void getProductAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("store", index_id);
Toast.makeText(getApplicationContext(),index_id, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getproductlist(map, new MyCallback<List<PosmultistoresModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Finding products....", GlobalVariables.SERVICE_MODE.GET_PRODUCTS));
}
// **this API have product Id's Details**
private void callSmbProductsAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("index_id", product);
//Toast.makeText(getApplicationContext(),added_by, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getSmbProduct(map, new MyCallback<List<PosSmbProductModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Fetching details....", GlobalVariables.SERVICE_MODE.SMB_PRODUCT));
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.AddtoBasket:
callPosProductsAPI();
callSmbProductsAPI();
break;
}
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
//Toast.makeText(getApplication(),"failure",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode) {
switch (mode) {
//** I'm setting data to spinner **
case GET_PRODUCTS:
try {
List<PosmultistoresModel> businessgroups = (List<PosmultistoresModel>) response.body();
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
ArrayAdapter<String> adapter1;
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, items);
//setting adapter to spinner
spinner.setAdapter(adapter1);
} catch (Exception e) {
e.printStackTrace();
}
break;**
// ** Product id details (title, image, etc) Api
case SMB_PRODUCT:
try {
ArrayList<PosSmbProductModel> products = (ArrayList<PosSmbProductModel>) response.body();
//Product_id = products.get(0).getProduct();
// for (int i = 0; i < products(); i++) {
Title = products.get(0).getTitle();
productname1.setText(Title);
imageid12 = products.get(0).getMain_image();
Picasso.with(this).load("https://www.consumer1st.in/pre_production/uploads/" + imageid12).into(imageid1);
}
// }
catch(Exception e)
{
e.printStackTrace();
}
break;
}
}
}
I am assuming that your product_name = businessgroups.get(0).getProduct(); is getting a pruduct.
First of all please remove this part
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
then can you try
ArrayList<String> productList = new ArrayList<>();
for (int i = 0; i < businessgroups.size(); i++) {
productList.add(businessgroups.get(i).getProduct());
}
And finally
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, productList);

Spinner not working in Android

There are two spinners in my application.when i select a value from one spinner, according to the selection, values will be loaded to second spinner. The problem is when i select the second spinner, the application unfortunately stops. Thanks in advance.
public class CreateAppointment extends AppCompatActivity {
String[] lect_name = new String[100];
String[] spinner_subjects_load;
Spinner spSubject,spLecturer;
String chosedSubject;
String chosedLectName;
String chosedDateString;
RequestQueue requestQueue;
String url = "http://quick-appointment.b2creations.net/getLecturerNames.php";
CustomRequest customRequest;
String dayOfWeekString;
Calendar currentDate,chosedDate;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_appointment);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
user = (User) intent.getExtras().getSerializable("user");
currentDate = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.format(currentDate.getTime()); //get current date
spinner_subjects_load = new String[]{"SPDC", "HCI", "MAD", "SEIII", "SEP", "DAA", "ITP"};
spSubject = (Spinner) findViewById(R.id.spSubject);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinner_subjects_load);
spSubject.setAdapter(adapter1);
requestQueue = Volley.newRequestQueue(this);
spSubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
chosedSubject = spSubject.getSelectedItem().toString();
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("subj_name", chosedSubject);
customRequest = new CustomRequest(Request.Method.POST, url, hashMap, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
int count = 0;
try {
JSONArray jsonArray = response.getJSONArray("Lecturers");
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
lect_name[count] = jo.getString("name");
count++;
}
spLecturer = (Spinner) findViewById(R.id.spLecturer);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(CreateAppointment.this, android.R.layout.simple_spinner_item, lect_name);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spLecturer.setAdapter(adapter2);
chosedLectName = spLecturer.getSelectedItem().toString();
Toast.makeText(CreateAppointment.this, chosedLectName, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(customRequest);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Looks like you initialize the second spinner spLecturer, and then immediately after you make a call to spLecturer.getSelectedItem().toString(), which I believe will return null at this point.
Perhaps you intended to add an OnItemSelectedListener to it first?

How to populate a ListView with Parse Array using ArrayAdapter

So I'm new to Android and I'm using Parse as my backend. I have an Array column in Parse called PrescriptionArray. I want to take the contents of this array (String values) and populate a listView with them. I think I'm only missing a couple of lines but not sure where? Any help would be greatly appreciated.. Thanks in advance!
public class PrescriptionsArrayActivity extends AppCompatActivity {
private ListView lvPrescriptions;
private EditText etMedicalID;
private ArrayAdapter<String> adapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prescriptions_array);
lvPrescriptions = (ListView) findViewById(R.id.lvPrescriptions);
etMedicalID = (EditText) findViewById(R.id.etMedicalID);
//Get the Medical ID number from previous activity
Bundle bundle = getIntent().getExtras();
String str = bundle.getString("MedicalID");
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
etMedicalID.setText(str);
final List<String> arrayprescription = new ArrayList<String>();
final ArrayAdapter adapter = new ArrayAdapter(PrescriptionsArrayActivity.this, android.R.layout.simple_list_item_1, arrayprescription);
final ParseQuery<ParseObject> query = ParseQuery.getQuery("PrescriptionObject");
query.whereEqualTo("MedicalID", etMedicalID.getText().toString());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> prescriptionList, ParseException e) {
if (e == null) {
for (int i = 0; i < prescriptionList.size(); i++) {
ParseObject p = prescriptionList.get(i);
if (p.getList("PrescriptionArray") != null) {
String s = arrayprescription.toString();
adapter.addAll(Arrays.asList(s));
}
}
lvPrescriptions.setAdapter(adapter);
}
}
});
}
}

Categories

Resources