How to update setListAdapter? - android

I am using setListAdapter for displaying the users online..
Here's my code:
Vector<String> myvector= Receiver.user;
int i =0;
String[] strings =new String[myvector.size()];
for(String str : myvector) {
strings[i] = str;
i++;
}
setListAdapter(new ArrayAdapter<String>(Display.this, android.R.layout.simple_list_item_1, strings));
The vector gets updated every time a new user comes online.But the display is not changing.
How to update it??
Thanks in advance

use the notifyDataSetChanged() of ArrayAdapter
Check here

Create your code as a method
for example
make it as
public void yourMethod()
{
Vector<String> myvector= Receiver.user;
int i =0;
String[] strings =new String[myvector.size()];
for(String str : myvector) {
strings[i] = str;
i++;
}
setListAdapter(new ArrayAdapter<String>(Display.this, android.R.layout.simple_list_item_1, strings));
}
call this Method.
When a user is created newly
so that it works

Related

Spinner default no selection when data fetched from json

Hi I asked this question before.But i didn't got a proper solution. I have a spinner which will load data from json.After selecting any item from spinner then it will post zeroth postition value again to another API.Everyting works fine.But my problem is I want defaultly no slection for spinner.I added a string named "no selection" to to zeroth position but it is not working.Please help me to implement this.
My spinner
void getList(){
final Common common = new Common();
int a= 100;
String webService = "API/Employee/GetList";
String postData = "";
String[] dataColumns = {"ID",//0
"Code",//1
"Name" ,//2
};
Runnable postThread = new Runnable() {
#Override
public void run() {
//Spinner
int a= 0;
ArrayList<String> Names = new ArrayList<String>();
for (int i=0;i<common.dataArrayList.size();i++){
String[] data=new String[3];
data[0]=common.dataArrayList.get(i)[0];
data[1]=common.dataArrayList.get(i)[1];
data[2]=common.dataArrayList.get(i)[2];
List.add(data);
}
for(int i=0;i<List.size();i++){
Names.add(List.get(i)[1]+" - "+List.get(i)[2]);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Insert.this, R.layout.item_spinner_black, Names);
dataAdapter.setDropDownViewResource(R.layout.item_spinner);
Spinner =(Spinner)findViewById(R.id.spinner);
//I added below code but it not working
// dataAdapter.insert(getString(R.string.selectemp), 0);
Spinner.setAdapter(dataAdapter);
}
My Post Data
postData="{\"Title\":\""+title.getText().toString()
+"\",\"Spinnervalue\":\""+List.get(Spinner.getSelectedItemPosition())[0]}
I think its help you.
ArrayList<String> Names = new ArrayList<String>();
Names.add("no selection");
for (int i=0;i<common.dataArrayList.size();i++){
String[] data=new String[3];
data[0]=common.dataArrayList.get(i)[0];
data[1]=common.dataArrayList.get(i)[1];
data[2]=common.dataArrayList.get(i)[2];
List.add(data);
}
for(int i=0;i<List.size();i++){
Names.add(List.get(i)[1]+" - "+List.get(i)[2]);
}
The problem is the initialization of your adapter. So when you add later the data, it will not have pre-selected item.
Edit:
I reordered your current code.
void getList(){
final Common common = new Common();
int a= 100;
String webService = "API/Employee/GetList";
String postData = "";
String[] dataColumns = {"ID",//0
"Code",//1
"Name" ,//2
};
Runnable postThread = new Runnable() {
#Override
public void run() {
//Spinner
int a= 0;
ArrayList<String> Names = new ArrayList<String>();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Insert.this, R.layout.item_spinner_black, Names);
dataAdapter.setDropDownViewResource(R.layout.item_spinner);
Spinner =(Spinner)findViewById(R.id.spinner);
//I added below code but it not working
// dataAdapter.insert(getString(R.string.selectemp), 0);
Spinner.setAdapter(dataAdapter);
for (int i=0;i<common.dataArrayList.size();i++){
String[] data=new String[3];
data[0]=common.dataArrayList.get(i)[0];
data[1]=common.dataArrayList.get(i)[1];
data[2]=common.dataArrayList.get(i)[2];
List.add(data);
}
for(int i=0;i<List.size();i++){
Names.add(List.get(i)[1]+" - "+List.get(i)[2]);
}
}
I added a dummy value.And It worked fine.
ArrayList<String> Names = new ArrayList<String>();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(Insert.this, R.layout.item_spinner_black, Names);
dataAdapter.setDropDownViewResource(R.layout.item_spinner);
Spinner =(Spinner)findViewById(R.id.spinner);
String[] data = new String[3];
data[0]="00000000-0000-0000-0000-000000000000";
data[1]="Select";
data[2]="Name";
List.add(data);
for (int i=0;i<common.dataArrayList.size();i++){
String[] data=new String[3];
data[0]=common.dataArrayList.get(i)[0];
data[1]=common.dataArrayList.get(i)[1];
data[2]=common.dataArrayList.get(i)[2];
List.add(data);
}
for(int i=0;i<List.size();i++){
Names.add(List.get(i)[1]+" - "+List.get(i)[2]);
}
Spinner.setAdapter(dataAdapter);

Why i am getting last value of an array in spinner?

Why i am getting only last value of an array. My array "arr" contains list of values but when i use it in spinner i am getting only last value of an array. Thanks in advance!!!
public void addItemsOnSpinner2(String[] arr) {
List list = new ArrayList(Arrays.asList(arr));
//System.out.println("Function Currency value===>"+list);
System.out.println("Function Currency value===>"+Arrays.toString(arr));
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
List<Currency> dataList = currencyExchange.getCurrencyList();
Iterator<Currency> iterator = dataList.iterator();
while (iterator.hasNext()) {
try {
//System.out.println("hhhhhhhhhhh=>" + iterator.next().getName());
currencyName= iterator.next().getName();
//String[] words=currencyName.split(" ");
arr=currencyName.split(" ");
System.out.println("Currencyname==>"+ Arrays.toString(arr));
}
catch (NoSuchElementException e){
System.out.println("Continue");
}
addItemsOnSpinner2(arr);
}
The reason you are only getting last value because in while loop you are using
one variable, so when you update new value of iterator into it, it is
replaced by old value
Convert your iterator to ArrayList like this :
Iterator<Currency> iterator = dataList.iterator();
List<String> arList= Lists.newArrayList(iterator);
Then call your method addItemsOnSpinner2(String[] arr) like this :
addItemsOnSpinner2(arList);
Edit:
Replace
while (iterator.hasNext()) {
try {
//System.out.println("hhhhhhhhhhh=>" + iterator.next().getName());
currencyName= iterator.next().getName();
//String[] words=currencyName.split(" ");
arr=currencyName.split(" ");
System.out.println("Currencyname==>"+ Arrays.toString(arr));
}
catch (NoSuchElementException e){
System.out.println("Continue");
}
addItemsOnSpinner2(arr);
with
String[] arr = dataList.toArray();
addItemsOnSpinner2(arr);

Extract substring from a string for spinner entry

I need to extract part of the string and display it in the spinner
I need that when the spinner display data example
For array entries like the following
"Equipo-001"
"Equipo-002"
Should show only:
"001"
"002"
Here's my code
private void rellenarSpinnerConFoliosDeMaquinasDelPunto(List<String> folios) {
maquinas = dbOn.getMaquinasDePunto(idPunto);
for (int i = 0; i < maquinas.size(); i++) {
foliosDeMaquinas.add(maquinas.get(i).getcFolioMaquina());
}
adaptadorFoliosMaquina = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, folios);
adaptadorFoliosMaquina.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn_folioMaquina.setAdapter(adaptadorFoliosMaquina);
spn_folioMaquina.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
ArrayList<String> numberFolios = new ArrayList<>();
for(int j =0; j < folios.size(); j++){
numberFolios.add(folios.get(j).substring(8, 10));
}
adaptadorFoliosMaquina = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, numberFolios);
Check link for better reference on how to use substring.
You can use SPLIT function
ArrayList<String> data = new ArrayList();
foreach(String get:folios){
data.add(folios.split("-")[1]);
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
If your result will be dynamic(The string length would vary in future) the below solution may work,
private void rellenarSpinnerConFoliosDeMaquinasDelPunto(List<String> folios) {
try{
maquinas = dbOn.getMaquinasDePunto(idPunto);
for (int i = 0; i < maquinas.size(); i++) {
foliosDeMaquinas.add(maquinas.get(i).getcFolioMaquina().toString().split("-")[1]);
}
} catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
adaptadorFoliosMaquina = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, folios);
adaptadorFoliosMaquina.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn_folioMaquina.setAdapter(adaptadorFoliosMaquina);
spn_folioMaquina.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

Issue with android spinners - Loading distinct values in spinners

I'm using two Spinners to show the items I'm getting from the json response. I have 2 problems right now. When u check my logcat u can see there are items repeating (Right side list, u can see so many pan). I want to have 1 item only once in my Spinner. I want to use something similar to distinct we use in sql databases.
My second problem is,
Select pan in the 1 spinner then 2nd spinner should contain items related to pan. (select pan in 1st spinner and 2nd should display only Pan large, pan medium and personal pan)
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> crust = new ArrayList<String>();
List<String> description = new ArrayList<String>();
List<String> extraDescription = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
JSONArray subMenuArray = object
.getJSONArray("SubMenuEntity");
for (int j = 0; j < subMenuArray.length(); ++j) {
JSONObject subMenuObject = subMenuArray
.getJSONObject(j);
Log.i("Crust", subMenuObject.getString("Crust"));
crust.add(subMenuObject.getString("Crust"));
Log.i("Description",
subMenuObject.getString("Description"));
description.add(subMenuObject.getString("Description"));
JSONArray extraItemEntityArray = subMenuObject
.getJSONArray("ExtraItemEntity");
}
}
crustSP = (Spinner) findViewById(R.id.sp_crust);
ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, crust);
dataAdapterCru
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crustSP.setAdapter(dataAdapterCru);
sizeSP = (Spinner) findViewById(R.id.sp_pizza_size);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
dataAdapterDes
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sizeSP.setAdapter(dataAdapterDes);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Output of this
Call this method to get distinct descriptions and then set the adapter using the return value of this function...
public static ArrayList<String> removeDuplicatesFromList(ArrayList<String> descriptions)
{
ArrayList<String> tempList = new ArrayList<String>();
for(String desc : descriptions)
{
if(!tempList.contains(desc))
{
tempList.add(desc);
}
}
descriptions = tempList;
tempList = null;
return descriptions;
}
For instance
description = Utils.removeDuplicatesFromList(description);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
NOTE:
I would suggest you make a new class call it Utils.java and place the above method inside it and then call it i have mentioned above.
Like this...
import java.util.ArrayList;
public class Utils
{
private Utils()
{
//Its constructor should not exist.Hence this.
}
public static ArrayList<String> removeDuplicatesFromList(ArrayList<String> descriptions)
{
ArrayList<String> tempList = new ArrayList<String>();
for(String desc : descriptions)
{
if(!tempList.contains(desc))
{
tempList.add(desc);
}
}
descriptions = tempList;
tempList = null;
return descriptions;
}
}
I hope it helps.

Split the string in java

String items={shoporder=shop1,shopname=abc,place=mmm};
I want to split the items as like (shop1).And assign to another string
String1=shop1
string2=abc
string3=mmm
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> userList = controller.getAllUsers();
// If users exists in SQLite DB
if (userList.size() != 0) {
// Set the User Array list in ListView
final ListAdapter adapter = new SimpleAdapter(second.this, userList, R.layout.view_user_entry, new String[] {
"shopId", "shopOrder","date","todayTarget","targetCompleted","shopHandled_person","shopName","salesmanName" }, new int[]
{ R.id.shopId,R.id.shopOrder,R.id.date,R.id.todayTarget,R.id.targetCompleted,R.id.shopHandled_person,R.id.shopName,R.id.salesmanName});
final ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String items=myList.getItemAtPosition(position).toString();
}
The string items contains all the list values.So i want to split the values and passed in to second activity.
The right way to initialize String array is,
String[] items=new String[]{"shopOrder=shop1","shopname=abc","place=mmm"};
simpler approach would be to use split method of String to split the string on =.
split method would break your String in two parts, one before = and second after = signs, i.e yourString.split("=")[0] <- part before = sign, yourString.split("=")[1] <- part after = sign.
for (int i =0; i<items.length; i++){
System.out.println(items[i].split("=")[1]);
}
OR
you can use yourString.indexOf("=")+1 to find every thing after = sign in your string, you can then use substring, to print everything after = signs,
substring(int beginIndex, int endIndex).
for (int i =0; i<items.length; i++){
System.out.println(items[i].substring(items[i].indexOf("=")+1, items[i].length()));
}
output in both cases
shop1
abc
mmm

Categories

Resources