Dynamic Spinners item selection error - android

I' am creating and populating spinners dynamically,the problem is while selecting the items(eg:4th) of any spinner ,i'am getting the id of the last spinners which is created dynamically item(4th id). I want to get the corresponding id's which i was set dynamically to the spinner items.
How to get the values of each spinner correctly..
Codes are give below.
public void secondarray(JsonParser jsonParser) {
String fieldName;
ameList = new ArrayList<AmeModel>();
AmeModel ameModel = null;
try {
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
ameModel = new AmeModel();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
fieldName = jsonParser.getCurrentName();
if ("valueid".equals(fieldName)) {
jsonParser.nextToken();
ameModel.setId((jsonParser.getText()));
} else if ("valuename".equals(fieldName)) {
jsonParser.nextToken();
ameModel.setName((jsonParser.getText()));
} else {
jsonParser.skipChildren();
}
}
ameList.add(ameModel);
}
Spinner sp=new Spinner(MainActivity.this);
AmeAdapter adapter = new AmeAdapter(this, ameList);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, ameList.get(i).getId(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
container.addView(sp);
//setContentView(linearlayout);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Any help will be appreciated thank you.

For get selected item Name:
String itemName=sp.getSelectedItem().toString(); // sp is your spinner
For get selected item position :
int position = sp.getSelectedItemPosition();
Now as per your code snippiest If you want to get Id Those you have set dynamically.
HashMap<String, String> nameId;
String itemId;
String itemName= String.valueOf(sp.getSelectedItem());
for (String s : nameId.keySet()) {
if (nameId.get(s).equals(itemName)) {
itemId= s;
}
Try to use above suggestion

Related

How to avoid data repetition in RecyclerView - Android?

I'm developing a wallpaper app using mongodb. I'm retrieving data from database and displaying it on my recyclerView by the help of a data-model class without any problem. Also I'm using swipe refresh layout to allow user for refreshing the recyclerView for new data.
But now the problem is how can I avoid data repetition and show only new posts to the user. I meant if there are 5 pics are there in my db in my first query I'll get those 5 so when the user will refresh the layout again the recyclerView's item is increased to 10 and I wanna avoid this I want to show them new pics only when the posts in db will be increased to 6 or more.
I think this data avoid concept is also used in social media apps. but for this context I wonder what I have to do?
Data model class:
public class TimelineData {
private String type, time, img_link;
public TimelineData(String type, String time, String img_link) {
this.type = type;//type means what type of wallpaper
this.time = time;
this.img_link = img_link;
}
public String getType() {
return type;
}
public String getTime() {
return time;
}
public String getImg_link() {
return img_link;
}
}
Adding Data to recyclerview:
private List<TimelineData> timelineDataList = new ArrayList<>();
public void onCreateView() {
recyclerview.setItemViewCacheSize(20);
recyclerview.setDrawingCacheEnabled(true);
recyclerview.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
recyclerview.setLayoutManager(new LinearLayoutManager(ctx));
//Setting Adapter
adapter=new CustomRecyclerViewAdapter(timelineDataList);
recyclerview.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
// Fetching data from server
socket.disconnect();
socket.connect();
//Getting Data from server
JSONObject obj=new JSONObject();
try {
obj.put("timeline_posts","all");
socket.emit("data",obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
void addTimelineData(String type,String time,String img_link) {
timelineDataList.add(new TimelineData(type,time,img_link));
adapter.notifyDataSetChanged();
}
private Emitter.Listener handlePosts = new Emitter.Listener() {
#Override
public void call(final Object... args){
try {
JSONArray jsonArray=(JSONArray)args[0];
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject ob=jsonArray.getJSONObject(i);
post_type=ob.getString("post_type");
post_time=ob.getString("time");
post_link=ob.getString("img_link");
addTimelineData(post_type,post_time,post_link);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("error",e.toString());
}
}
};
You can try cleaning the data source whenever you get new data, that way you'll always reinsert the complete dataset, if you have new data it will be inserted with the old one and you don't have to worry about repeated data in the mobile app, only in the server.
private List<TimelineData> timelineDataList=new ArrayList<>() ;
public void onCreateView(){
recyclerview.setLayoutManager(new LinearLayoutManager(ctx));
//Setting Adapter
adapter=new CustomRecyclerViewAdapter(timelineDataList);
recyclerview.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
// Fetching data from server
socket.disconnect();
socket.connect();
//Getting Data from server
JSONObject obj=new JSONObject();
try {
obj.put("timeline_posts","all");
socket.emit("data",obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
void addTimelineData(String type,String time,String img_link){
boolean isRepeated = false;
for(TimelineData data : timelineDataList){
if(data.getTime().equals(time)){
isRepeated = true;
}
}
if(!isRepeated){
timelineDataList.add(new TimelineData(type,time,img_link));
}
adapter.notifyDataSetChanged();
}
private Emitter.Listener handlePosts = new Emitter.Listener(){
#Override
public void call(final Object... args){
try {
JSONArray jsonArray=(JSONArray)args[0];
timelineDataList.clear(); //clear data before inserting new one
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject ob=jsonArray.getJSONObject(i);
post_type=ob.getString("post_type");
post_time=ob.getString("time");
post_link=ob.getString("img_link");
addTimelineData(post_type,post_time,post_link);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("error",e.toString());
}
}
};
before you add new elements to the wallpaper list, check to see if an object with that id exist in the list. if it does, skip it, else add it.

Methods of Fragment class in android not getting called

Hi I am a beginner for android and in my app I have to show SlidingPaneLayout at right side.
So far everything is OK.
But when I tap on SlidingPaneLayout of any row I want to reload Listview for this I wrote below code.
But here Listview is reloading by default, but when I tap on SlidingPaneLayout it's not reloading.
Below lines are not executing when I call getAllTips() method from MainActivity.
if (friendArrayList.size() != 0) {
Log.d("=======>" ," data Available");
 ˚
adapter.notifyDataSetChanged();
}else{
Log.d("=======>" ,"No data Available");
}
ListViewFragment:-
public class ListViewFragment extends Fragment implements AsyncTaskClass.BackGroundServiceCall {
private ArrayList<MyTripBean> friendArrayList;
ListViewAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.listview_layout,container,false);
ListView listView = (ListView)view.findViewById(R.id.list_item);
//set ListView header:-
inflater = getActivity().getLayoutInflater();
View header = inflater.inflate(R.layout.header_listview,listView,false);
listView.addHeaderView(header);
//adapter = new ListViewAdapter(getActivity(), R.layout.item_listview, friendArrayList);
friendArrayList = new ArrayList<MyTripBean>();
adapter = new ListViewAdapter(getActivity(),
R.layout.list_item, friendArrayList);
listView.setAdapter(adapter);
getAllTips(getActivity(),9); //Getting friendArrayList data from Services
return view;
}
// get all trips of the User
public void getAllTips(Activity activity,int tripstatus) {
try {
JSONObject json = new JSONObject();
json.put("TripStatus", tripstatus);
json.put("medicaidId", "104584743999");
if (CommonUtilities.isNetWorkStateAvailble(activity)) {
AsyncTaskClass task = new AsyncTaskClass(this, activity,
json);
task.execute(ServiceUrl.GET_ALL_TRIPS, "1",
"Token");
} else {
Log.d("==========>", "There is Network Error");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void doPostExecute(StatusObject statusObject) {
// TODO Auto-generated method stub
if (statusObject != null) {
if (statusObject.getResponseCode() == 401) {
Log.d("==========>", "Session Has been Expired");
} else if (statusObject.getResponseCode() == 200) {
handleResponseData(statusObject.getMessage());
} else {
Log.d("==========>", "Server not responding. Please try again later.");
}
} else {
Log.d("==========>", "Server not responding. Please try again later.");
}
}
// handle the response
public void handleResponseData(String result) {
Log.d("Final Json==========>", result);
try {
Object json = new JSONTokener(result).nextValue();
if (json instanceof JSONObject) {
// you have an object
JSONObject jsonObject = new JSONObject(result);
if (jsonObject.has("Error")) {
if (jsonObject.getString("Error").equalsIgnoreCase("true")) {
if (jsonObject.has("message")) {
Log.d("==========>", "there is erorr mesage coming from server");
}
}
}
} else if (json instanceof JSONArray) {
// you have an array
handleTripsResponse(result);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// handle the json array data
public void handleTripsResponse(String result) {
try {
Type type = new TypeToken<List<MyTripBean>>() {
}.getType();
ArrayList<MyTripBean> newListData = new Gson().fromJson(result, type);
friendArrayList.addAll(newListData);
if (friendArrayList.size() != 0) {
Log.d("=======>" ," data Available");
adapter.notifyDataSetChanged();
}else{
Log.d("=======>" ,"No data Available");
}
} catch (Throwable throwable) {
}
}
}
MainActivity:-
public class MainActivity extends AppCompatActivity {
SlidingPaneLayout mSlidingPanel;
ListView mMenuList;
String [] MenuTitles = new String[]{"First Item","Second Item","Third Item","Fourth Item"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListViewFragment fragment1 = new ListViewFragment();
fragment1.getAllTips(MainActivity.this,8);
}
});
}
The code looks fine. OnItemClickListeners looks fine for the listview and will work correctly.
I doubt if you are getting exception in method handleTripsResponse(). please try printing log in the catch block of this method. then you will come to know the exception and how to resolve it.
Also in your MainActivity, in onItemClickListener, do not create a new instance of the ListViewFragment, instead use the instance of fragment which you attached in fragment transaction.
ListViewFragment fragment1 = new ListViewFragment();
fragment1.getAllTips(MainActivity.this,8);

found index 0, size is 0 in android

"There i found index out of bound exception how can i solve???"
public static void addToCart() {
ArrayList<ItemData> iArr;
if (holdSelection != null) {
String categoryID = holdSelection.getCategoryID();
int position = categoriesAddedd.indexOf(holdSelection.getCategoryID());
int itemPosition =categoriesitemAddedd.indexOf(holdSelection.getItemData().get(0).getItemID());
if (!categoriesAddedd.contains(categoryID)) {
CategoryData data = new CategoryData();
data.setCategoryID(categoryID);
data.setCategoryName(holdSelection.getCategoryName());
data.setItemData(holdSelection.getItemData());
mAddedToCart.add(data);
categoriesAddedd.add(categoryID); categoriesitemAddedd.add(holdSelection.getItemData().get(0).getItemID());
Toast.makeText(mContext,R.string.Add_to_cart,Toast.LENGTH_SHORT).show();
} else {
if (position>=0) {
if(itemPosition>=0){
if(holdSelection.getItemData().get(0).getScaled()){
Toast.makeText(mContext,R.string.Already_in_cart,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(mContext,R.string.Already_in_cart,Toast.LENGTH_SHORT).show();
}
}else{
try{
CategoryData data = mAddedToCart.get(position);
iArr = data.getItemData();
iArr.add(holdSelection.getItemData().get(0));
categoriesAddedd.add(categoryID);
categoriesitemAddedd.add(holdSelection.getItemData().get(0).getItemID());
Toast.makeText(mContext, R.string.Add_to_cart,Toast.LENGTH_SHORT).show();
}catch (Exception e) {
// TODO: handle exception
Toast.makeText(mContext, "There is " +e,Toast.LENGTH_SHORT).show();
System.out.println("Exception : "+ e.getMessage());
e.printStackTrace();
}
}
}
}
}
}
It's impossible to help without a minimum of (structured) information (and also without a Hello, please, tank you, polite words if you prefer).
First of all, you have to use the brackets to display code when you post, so your clean code should appear as follow :
public static void addToCart() {
ArrayList iArr;
if (holdSelection != null) {
String categoryID = holdSelection.getCategoryID();
int position = categoriesAddedd.indexOf(holdSelection.getCategoryID());
int itemPosition =categoriesitemAddedd.indexOf(holdSelection.getItemData().get(0).getItemID());
if (!categoriesAddedd.contains(categoryID)) {
CategoryData data = new CategoryData();
data.setCategoryID(categoryID);
data.setCategoryName(holdSelection.getCategoryName());
data.setItemData(holdSelection.getItemData());
mAddedToCart.add(data);
categoriesAddedd.add(categoryID);
categoriesitemAddedd.add(holdSelection.getItemData().get(0).getItemID());
Toast.makeText(mContext,R.string.Add_to_cart,Toast.LENGTH_SHORT).show();
} else {
if (position>=0) {
if(itemPosition>=0){
if(holdSelection.getItemData().get(0).getScaled()){
Toast.makeText(mContext,R.string.Already_in_cart,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(mContext,R.string.Already_in_cart,Toast.LENGTH_SHORT).show();
}
}else{
try{
CategoryData data = mAddedToCart.get(position);
iArr = data.getItemData(); iArr.add(holdSelection.getItemData().get(0));
categoriesAddedd.add(categoryID);
categoriesitemAddedd.add(holdSelection.getItemData().get(0).getItemID());
Toast.makeText(mContext, R.string.Add_to_cart,Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{ // TODO: handle exception Toast.makeText(mContext, "There is " +e,Toast.LENGTH_SHORT).show();
System.out.println("Exception : "+ e.getMessage()); e.printStackTrace();
}
}
}
}
}
}
then my first question will be : what is holdSelection related to?
Please add more parts of your code as your log (asked by Remees).
Alex.

Show dropdown after dynamic loading

I load dynamically the string of my autocomplete with JSON objects, but the list appears only in the next character; How can I make my list appear exactly after the loading?
This process is called from a onTextChanged event. I tried to force display with showDropDown() but didn't work!!!
Any help?
public class HttpConnectionApiActivity extends Activity implements HttpListner, TextWatcher {
.....
AutoCompleteTextView from_txt;
List<String> country_List;
ArrayAdapter<String> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
from_txt = (AutoCompleteTextView) findViewById(R.id.from_txt);
//from_txt.setThreshold(1);
prepareCountryList();
from_txt.addTextChangedListener( this);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,country_List);
from_txt.setAdapter(adapter);
}
....
public void notifyHTTPRespons(final HttpHandler http) {
public void run() {
String result = http.getResponse();
try {
adapter.clear();
for (int i = 0; i < results_Array.length(); i++) {
JSONObject row = results_Array.getJSONObject(i);
String name=row.getString("name");
adapter.add(name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I could display the dropdown list by adding these 2 lines :
It's very simple hack by resetting text when you get updated data.
try {
adapter.clear();
for (int i = 0; i < results_Array.length(); i++) {
JSONObject row = results_Array.getJSONObject(i);
String name=row.getString("name");
adapter.add(name);
}
//____________________
adapter.notifyDataSetChanged();
from_txt.setText(from_txt.getText());
//____________________
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Android: how to get spinner value and check the condition

In my app i have a spinner with two items ..i have to choose the item an do action accordingly
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String Comment = edittext.getText().toString();
String choose = spinner.getSelectedItem()
.toString();
if (Comment != null && Comment.equalsIgnoreCase("")){
post(Comment,choose);
getActivity().finish();
}else{
showToast("Please enter you comment!");
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
} catch (Exception e) {
e.printStackTrace();
getActivity().finish();
}
}
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
-----------------> if(spinner.getSelectedItem().toString().equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}
private void publishStory(Bundle postParams,final String comments,final String choose) {
Session session = Session.getActiveSession();
if (session != null){
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
Request.Callback callbackRequest= new Request.Callback() {
public void onCompleted(Response response) {
if (response == null || response.equals("")
|| response.equals("false")) {
showToast("Blank response.");
} else
new fbUtils(activity).share(Data, comments, response.getError(),choose);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
};
Request request = new Request(session, Constants.fb.fbId + "/comments", postParams,
HttpMethod.POST, callbackRequest);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
the issue is the post() is not executing when clicking the dailogbutton its going into else part, i want to execute the if condition in post() method, Any help is appreciated
As you are getting the value from the spinner. The value may not be updated one .
You should use item-selected listeners.
String result="";
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
// Your variable should update here
result = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Now use that value in onPost method as:
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
Log.v("TEST",spinner.getSelectedItem().toString());
-----------------> if(result.equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}
Try like this:
private Spinner status;
status = (Spinner) findViewById(R.id.status);
final ArrayList<Simplestatus> statusList = new ArrayList<Simplestatus>();
Simplestatus tempstatus = new Simplestatus();
tempstatus.setSimpleStatusName("ZERO");
tempstatus.setSimpleStatusValue("0");
Simplestatus tempstatus1 = new Simplestatus();
tempstatus1.setSimpleStatusName("ONE");
tempstatus1.setSimpleStatusValue("1");
statusList.add(tempstatus);
statusList.add(tempstatus1);
SpinnerAdapter stateAdaptor = new SpinnerAdapter(SettingActivity.this,statusList);
// stateList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
status.setAdapter(stateAdaptor);
status.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
changeStatus(statusList.get(position));
selected = statusList.get(position).getsimpleStatusName();
System.out.println("selected"+selected);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
public class Simplestatus
{
private String simpleStatusName;
private String simpleStatusValue;
public String getSimpleStatusName()
{
return simpleStatusName;
}
public void setSimpleStatusName(String simpleStatusName)
{
this.simpleStatusName = simpleStatusName;
}
public String getsimpleStatusValue()
{
return simpleStatusValue;
}
public void setsimpleStatusValue(String simpleStatusValue)
{
this.simpleStatusValue = simpleStatusValue;
}
}

Categories

Resources