How to get child class objects from array list? - java

I am having trouble getting the earlier class objects of an array list in the 'onPostExecute' method of my asynch class. To simplify things for this post, I'm just trying to set the text of the 'name' to my textview in my onPostExecute method like so.
myTextView.setText(VideoDetail_List.get(0).getVideoName());
However the problem is that the String that is returning is the last instance of the videoname object in the string array, instead of the first instance of the video name, which should be the child class object of the VideoDetail_List at the 0 index.
AsyncTask Class
final JSONObject obj = new JSONObject(result);
final JSONArray videoData = obj.getJSONArray("data");
final int n = videoData.length();
for (int i = 0; i < n; ++i) {
final JSONObject video = videoData.getJSONObject(i);
videoDetail.setVideoName(video.getString("name"));
videoDetail.setVideoDuration(video.getString("duration"));
final JSONObject videoPictures = video.getJSONObject("pictures");
final JSONArray videoPictureSizes = videoPictures.getJSONArray("sizes");
final JSONObject videoPictureLink = videoPictureSizes.getJSONObject(1);
videoDetail.setPictureLink(videoPictureLink.getString("link"));
//pictureLink.add(videoPictureLink.getString("link"));
final JSONArray videoURLTypes = video.getJSONArray("download");
final JSONObject videoURLLink = videoURLTypes.getJSONObject(0);
videoDetail.setVideoLink(videoURLLink.getString("link"));
//videoLink.add(videoURLLink.getString("link"));
VideoDetail_List.add(i,videoDetail);
}
return VideoDetail_List;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(List<VideoDetail> VideoDetail_List) {
System.out.println("RESPONSE: " + VideoDetail_List);
final TextView myTextView = new TextView(mContext);
myTextView.setText(VideoDetail_List.get(0).getVideoName());
mLayout.addView(myTextView);
myTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sText = myTextView.getText().toString();
//Toast toast = Toast.makeText(this, sText, Toast.LENGTH_SHORT);
Toast toast = Toast.makeText(mContext, sText, Toast.LENGTH_LONG);
toast.show();
}
});
}
VideoDetail Class
public class VideoDetail {
private String videoName;
private String videoDuration;
private String pictureLink;
private String videoLink;
public String getVideoName() {
return this.videoName;
}
public void setVideoName(String videoName) {
this.videoName = videoName;
}
public String getVideoDuration() {
return videoDuration;
}
public void setVideoDuration(String videoDuration) {
this.videoDuration = videoDuration;
}
public String getPictureLink() {
return pictureLink;
}
public void setPictureLink(String pictureLink) {
this.pictureLink = pictureLink;
}
public void setVideoLink(String videoLink){
this.videoLink = videoLink;
}
public String getVideoLink() {
return videoLink;
}
}
Thank you in advance for your help!

However the problem is that the String that is returning is the last
instance of the videoname object in the string array
That's because you are overriding the content of the only instance of VideoDetails at every iteration of your for loop. You should instantiate it at every iteration
for (int i = 0; i < n; ++i) {
videoDetail = new VideoDetail();

Related

How to setText to ArrayList<>?

I have a class Tweet with a get Mentions methods with it
But I don't know how to setText to the ArrayList<>.
Here is my code
public class Tweet {
public String body;
private long uid;
private String createAt;
private User user;
private String urlImageNews;
private static String url;
public ArrayList<User> mentions;
public ArrayList<User> getMentions()
{
return mentions;
}
public String getUrlImageNews()
{
return urlImageNews;
}
public String getBody() {
return body;
}
public long getUid() {
return uid;
}
public String getCreateAt() {
return createAt;
}
public User getUser() {
return user;
}
public String getUrl()
{
return url;
}
public String getRelativeTimeAgo() {
String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH);
sf.setLenient(true);
String relativeDate = "";
try {
long dateMillis = sf.parse(getCreateAt()).getTime();
relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return relativeDate;
}
public static Tweet fromJSON(JSONObject jsonObject)
{
Tweet twt = new Tweet();
try {
twt.body = jsonObject.getString("text");
twt.uid = jsonObject.getLong("id");
twt.createAt = jsonObject.getString("created_at");
twt.user = User.fromJSON(jsonObject.getJSONObject("user"));
twt.mentions = LoadMentions(jsonObject);
JSONArray media = jsonObject.getJSONObject("entities").optJSONArray("media");
if (media != null) {
for (int i = 0; i < media.length(); i++) {
JSONObject a = media.getJSONObject(i);
if (a.getString("type").equals("photo")) {
twt.urlImageNews = a.getString("media_url_https");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return twt;
}
private static ArrayList<User> LoadMentions(JSONObject object) throws JSONException{
if (!object.getJSONObject("entities").has("user_mentions")) {
return null;
}
ArrayList<User> mentions = new ArrayList<User>();
JSONArray mentionsJSON = object.getJSONObject("entities").getJSONArray("user_mentions");
for (int i = 0; i < mentionsJSON.length(); i++) {
User user = User.fromJSON(mentionsJSON.getJSONObject(i));
mentions.add(user);
}
return mentions;
}
public static ArrayList<Tweet> fromJSONArray(JSONArray jsonArray)
{
ArrayList<Tweet> tweets = new ArrayList<>();
for ( int i = 0 ; i < jsonArray.length(); i++)
{
try {
JSONObject tweetjson = jsonArray.getJSONObject(i);
Tweet tweet = Tweet.fromJSON(tweetjson);
if(tweet != null)
{
tweets.add(tweet);
}
} catch (JSONException e) {
e.printStackTrace();
continue;
}
}
return tweets;
}
}
Here is my MentionsAdapter where I want to setText the Mentions Array
public class MentionsAdapter extends RecyclerView.Adapter<MentionsAdapter.ViewHolder> {
Context context;
View tweetView;
private List<Tweet> lTweets;
public MentionsAdapter(List<Tweet> tweets)
{
lTweets = tweets;
}
public void clear() {
lTweets.clear();
notifyDataSetChanged();
}
// Add a list of items
public void addAll(List<Tweet> list) {
lTweets.addAll(list);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView ivProfile;
private TextView tvUsername;
private TextView tvMentions;
private TextView tvMentionsDate;
public ViewHolder(View view) {
super(view);
ivProfile = (ImageView) view.findViewById(R.id.ivAva);
tvUsername = (TextView) view.findViewById(R.id.tvName);
tvMentions = (TextView) view.findViewById(R.id.tvMentions);
tvMentionsDate = (TextView) view.findViewById(R.id.tvMentionsDate);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
tweetView = inflater.inflate(R.layout.item_metions, parent, false);
ViewHolder viewHolder = new ViewHolder(tweetView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("debug", "int:: " + position);
Tweet tweet = lTweets.get(position);
holder.tvMentionsDate.setText(tweet.getRelativeTimeAgo());
holder.tvUsername.setText(tweet.getUser().getName());
holder.tvMentions.setText(tweet)
holder.ivProfile.setImageResource(android.R.color.transparent);
Glide.with(context).load(tweet.getUser().getProfileImageUrl()).into(holder.ivProfile);
}
#Override
public int getItemCount() {
if(lTweets == null){
Log.d("debug", "null");
return 0;
}
else {
Log.d("debug", ":: " + lTweets.size());
return lTweets.size();
}
}
}
Thanks in advance.
you can get mentions data from tweet by following
User user = tweet.getMentions();
so that you can get user object from that.same way you can get all user instances from here by using
user.getMethodName()
just update the above code in onBindViewHolder().
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("debug", "int:: " + position);
Tweet tweet = lTweets.get(position);
User user = tweet.getMentions();
holder.tvMentionsDate.setText(tweet.getRelativeTimeAgo());
holder.tvUsername.setText(tweet.getUser().getName());
holder.tvMentions.setText(tweet)
holder.ivProfile.setImageResource(android.R.color.transparent);
Glide.with(context).load(tweet.getUser().getProfileImageUrl()).into(holder.ivProfile);
}
If i am not wrong u want to add data to your ArrayList which is of type Tweet this can be done like this
yourArrayList.add(new Tweet ("Parameters goes here");
hope this helps
if I understand correctly you just want to display the number of mentions.
you can do this:
holder.tvMentions.setText(Integer.toString(tweet.getMentions().size()));
Ahh Well I fix with my answer just by adding some line :
twt.textMentions = jsonObject.getString("text");
Anyway thanks everyone for the answers

How can I use a string from an array in one method in another?

I have an array as shown below
private ArrayList<Blogs> parseJSONResponseCar(JSONArray response) {
if (!response.equals("")) {
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String Blue = currentQuestions.getString("text");
String Yellow=currentQuestions.getString("id");
How can I extract the getString("id") value and put it in a new OnClick Listener method??
public void OnUp (View view) {}
Use a global class variable outside function like this:
string globalVar = "";
private ArrayList<Blogs> parseJSONResponseCar(JSONArray response) {
String Yellow=currentQuestions.getString("id");
globalVar = Yellow;
}
public void OnUp (View view) {
string test = globalVar ;
}
If its a web application you can store in Session.

Convert JSON values from Integer to String

I am using an AsyncTask to connect to the following URL:
https://api.themoviedb.org/3/movie/upcoming?api_key=6572f232190d6b55ec917726dab87783
One of the values I am having trouble with is the genre_id. As it is a JSONArray I add the values to an ArrayList. I then later want to convert these values to the String correspondence which are found here:
http://api.themoviedb.org/3/genre/movie/list?api_key=6572f232190d6b55ec917726dab87783
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre_ids");
ArrayList<Integer> genre = new ArrayList<Integer>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add(genreArry.optInt(j));
}
I'm just wondering what is the best way to do this? I am a displaying a ListView of all the information and for each row all the information is correct. I just need to convert the Genre id into the corresponding String. I have tried the code below but the TextView is always overwritten by the last value. Does anyone know of a better way to do this?
private void getGenre(int genre) {
for (int i = 0; i < genreList.size(); i++) {
Log.d("THE", "THE GENRE ADAPTER RETRIEVED IS" + i + genreList.get(i).getId() + genreList.get(i).getName());
if (genreList.get(i).getId() == genre) {
String name = genreList.get(i).getName();
mGenre.setText(name);
}
}
Solved.
I managed to get this working by doing a check in the onPostExecute of my AsyncTask
try {
JSONObject json = new JSONObject(result);
JSONArray movies = json.getJSONArray("results");
for (int i = 0; i < movies.length(); i++) {
JSONObject obj = movies.getJSONObject(i);
//Create Movie Object
Movie movie = new Movie();
//get values from JSON
movie.setTitle(obj.getString("original_title"));
movie.setPopularity(obj.getString("popularity"));
movie.setYear(obj.getString("release_date"));
movie.setThumbnailUrl(obj.getString("poster_path"));
movie.setOverView(obj.getString("overview"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre_ids");
ArrayList<Integer> genre = new ArrayList<Integer>();
ArrayList<String> genreName = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add(genreArry.optInt(j));
for (int zz = 0; zz < myGenreList.size(); zz++) {
if (myGenreList.get(zz).getId() == genre.get(j)) {
String name = myGenreList.get(zz).getName();
genreName.add(name);
}
}
}
movie.setGenre(genre);
movie.setGenreName(genreName);
I prefer Volley instead of AsyncTask for simplicity, but you are more than welcome to use either. Note, AsyncTask will require quite a bit more work.
From what I have provided here, you should be able to get my screenshot after building the ListView item XML.
I loosely followed this guide to get started quickly.
Screenshot
Movie.java - Model Object
public class Movie {
private int id;
private String title;
private List<String> genres;
public Movie() {
this(-1, null);
}
public Movie(int id, String title) {
this.id = id;
this.title = title;
this.genres = new ArrayList<String>();
}
public void addGenre(String s) {
this.genres.add(s);
}
public String getTitle() {
return title;
}
public List<String> getGenres() {
return genres;
}
}
MovieAdapter.java - ListView adapter
public class MovieAdapter extends ArrayAdapter<Movie> {
private final int layoutId;
public MovieAdapter(Context context, List<Movie> objects) {
super(context, 0, objects);
layoutId = R.layout.item_movie;
}
private static class ViewHolder {
TextView title;
TextView genres;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Movie movie = getItem(position);
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layoutId, parent, false);
viewHolder.title = (TextView) convertView.findViewById(R.id.movie_title);
viewHolder.genres = (TextView) convertView.findViewById(R.id.movie_genres);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.title.setText(movie.getTitle());
viewHolder.genres.setText(String.valueOf(movie.getGenres()));
// Return the completed view to render on screen
return convertView;
}
}
MainActivity.java
public class MainActivity extends Activity {
private static final String GENRES_URL = "http://api.themoviedb.org/3/genre/movie/list?api_key=6572f232190d6b55ec917726dab87783";
private static final String MOVIES_URL = "https://api.themoviedb.org/3/movie/upcoming?api_key=6572f232190d6b55ec917726dab87783";
private HashMap<Integer, String> genreMap = new HashMap<Integer, String>();
private List<Movie> movies = new ArrayList<Movie>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
final MovieAdapter movieAdapter = new MovieAdapter(this, movies);
lv.setAdapter(movieAdapter);
// Build the genres map
JsonObjectRequest request1 = new JsonObjectRequest(GENRES_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray genres = response.getJSONArray("genres");
for (int i = 0; i < genres.length(); i++) {
JSONObject genre = genres.getJSONObject(i);
int id = genre.getInt("id");
String name = genre.getString("name");
genreMap.put(id, name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Network error", error.getMessage());
}
}
);
VolleyApplication.getInstance().getRequestQueue().add(request1);
JsonObjectRequest request2 = new JsonObjectRequest(MOVIES_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
movieAdapter.clear();
try {
JSONArray results = response.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
int movieId = result.getInt("id");
String title = result.getString("original_title");
Movie movie = new Movie(movieId, title);
JSONArray genreIds = result.getJSONArray("genre_ids");
for (int j = 0; j < genreIds.length(); j++) {
int id = genreIds.getInt(j);
String genre = genreMap.get(id);
movie.addGenre(genre);
}
movieAdapter.add(movie);
}
} catch (JSONException e) {
Log.e("JSONException", e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Network error", error.getMessage());
}
}
);
VolleyApplication.getInstance().getRequestQueue().add(request2);
}
}

removing words from a string in java

Could anyone tell me what is wrong in my code?
I am trying to pass a string to function removeWords() and this function removes some information from the String.
For example if I pass:
"I Have a Headach"
the function should return:
"Headach"
However, my function is not working:
public class WordChosen extends Activity {
private TextView wordsList;
private String symptom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word_chosen);
//Getting String from VoiceRecognition Activity and displaying it
Intent intent = getIntent();
String wordChosen = intent.getExtras().getString("wordChosen");
//casting the string with TextView to display the result
wordsList = (TextView) findViewById(R.id.wordChosen);
Log.v("Word List:", "+++++"+wordChosen);
//Setting text to be displayed in the textView
removeWords(wordChosen);
Log.v("removewords:", "------- message is displayed");
}
public void removeWords(String wordList)
{
ArrayList<String> stopList = null;
stopList.add("i");
stopList.add("have");
stopList.add("a");
ArrayList<String> result = new ArrayList<String>(Arrays.asList(wordList.split(" ")));
for(int i=0; i<result.size();i++)
{
for(int j=0; j<stopList.size();j++)
{
if (result.get(i).equals(stopList.get(j))) {
break;
}
else {
if(j==stopList.size()-1)
{
wordsList.setText(result.get(i));
}
}
}
}
}
}
public static void main(String[] args) {
String word = "I Have a Headach";
String remove = "I Have a ";
System.out.println(removeWords(word, remove));
}
public static String removeWords(String word ,String remove) {
return word.replace(remove,"");
}
output : Headach

How to pass selected parents "child elements" from one custom adapter to another new custom adapter?

I am having a custom adapter with checkbox and child elements in an expandable custom adapter, and when the parent items - for my case Orders are selected /checked the Orders are passed to a new custom adapter without checkbox . I am able pass the parent ie Orders but i am not able to pass the Child elements ie Items which are the childreen of ORDERS. So i need to pass the child elements of the orders that are selected to the new adapter view.
My code :
try {
System.out.println("READ/PARSING JSON");
serverStatus = jobj.getString("SERVER_STATUS");
System.out.println("serverStatusObj: "+serverStatus);
JSONArray serverResponseArray2=jobj.getJSONArray("SERVER_RESPONSE");
for (int m = 0; m < serverResponseArray2.length(); m++) {
String SERVER_RESPONSE = serverResponseArray2.getString(m);
JSONObject Open_Orders_obj = new JSONObject(SERVER_RESPONSE);
mMAX_ORDERS_TOBEPICKED = Open_Orders_obj.getInt("MAX_ORDERS_TOBEPICKED");
JSONArray ja = Open_Orders_obj.getJSONArray("ORDER_ITEM_DETAILS");
order_Item_Values.clear();
mOpenOrders = new ArrayList<OpenOrders>(ja.length());
for(int i=0; i<ja.length(); i++){
String ORDER_ITEM_DETAILS = ja.getString(i);
jobj1 = new JSONObject(ORDER_ITEM_DETAILS);
String ORDERNAME = jobj1.getString("ORDERNAME");
String ORDERID = jobj1.getString("ORDERID");
final OpenOrders parent = new OpenOrders();
parent.setOrderName(ORDERNAME+ " "+ i);
parent.setOrderID(ORDERID);
parent.setChecked((i % 2) == 0);
OpenOrders openOrderObj= new OpenOrders(ORDERID,ORDERNAME);
JSONArray Order_Items = jobj1.getJSONArray("ITEMS");
itemList =new ArrayList<String>();
parent.setChildren(new ArrayList<Child>());
for(int k=0; k<Order_Items.length(); k++){
String ITEMS = Order_Items.getString(k);
System.out.println(ITEMS);
ItemObj = new JSONObject(ITEMS);
String ITEMNUMBER = ItemObj.getString("ITEMNUMBER");
String ITEMNAME = ItemObj.getString("ITEMNAME");
itemList.add(ITEMNAME);//This adds item name's to the ArrayList named 'itemList'
openOrderObj.setItemID(ITEMNUMBER);
openOrderObj.setItemName(ITEMNAME);
System.out.println("item name"+ITEMNAME);
final Child child = new Child();
child.setName(ITEMNAME + i + "/" + k);
parent.getChildren().add(child);
}
mOpenOrders.add(parent);
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //***End code to read json content from text file saved in device
enter code here
My open Order class:
import java.io.Serializable;
import java.util.ArrayList;
import com.kits.ddf_order_model.Child;
public class OpenOrders implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String orderID;
private String orderName;
private boolean selected;
private boolean checked;
private ArrayList<Child> children;
private String itemID;
private String itemName;
public OpenOrders(String orderID, String orderName) {
super();
this.orderID = orderID;
this.orderName = orderName;
}
public OpenOrders() {
// TODO Auto-generated constructor stub
}
public String getOrderID() {
return orderID;
}
public void setOrderID(String orderID) {
this.orderID = orderID;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
#Override
public String toString() {
return this.orderName;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public ArrayList<Child> getChildren()
{
return children;
}
public void setChildren(ArrayList<Child> children)
{
this.children = children;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
my Child class:
public class Child
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
So When the button is clicked what i do is :
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mAdapter != null) {
int isSelectedOrderNumber=0;//This Variable will check with the parameter passed from server
mOpenOrdersSelected = new ArrayList<OpenOrders>();
StringBuffer sb = new StringBuffer();
Iterator<OpenOrders> it = mOpenOrders.iterator();
while(it.hasNext())
{
OpenOrders objOpenOrders = it.next();
//Do something with objOpenOrders
if (objOpenOrders.isChecked()) {
isSelectedOrderNumber++;
// mOpenOrdersSelected.add(new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName()));
sb.append(objOpenOrders.getOrderID());
sb.append(",");
final OpenOrders parent = new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName());
ArrayList<Child> mOpenOrderItems=objOpenOrders.getChildren();
Iterator<Child> i = mOpenOrderItems.iterator();
mOpenOrdersSelected.add(parent);
}
}
//Below Condition Will Check the selected Items With parameter passed "mMAX_ORDERS_TOBEPICKED"
if(isSelectedOrderNumber<1){
ShowErrorDialog("Please Select atleast One order");
return;
}
if(isSelectedOrderNumber>mMAX_ORDERS_TOBEPICKED){
ShowErrorDialog(" Select Maximum of "+mMAX_ORDERS_TOBEPICKED+ " Orders only to process");
return;
}
//Below code is to Call again the adapter and Displays the Order's which are checked/selected.
expListView = (ExpandableListView) findViewById(R.id.expandable_order_item_list);
ExpandableOrderSelectedListAdapter mOrderSelectedAdapter = new ExpandableOrderSelectedListAdapter(SelectLocationActivity.this,mOpenOrdersSelected);
expListView.setAdapter(mOrderSelectedAdapter);
expListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//nothing to do , as Null Pointer exception Occurred ,to avoid that I just used this "setOnItemClickListener"
}
});
button.setVisibility(View.GONE);//Hide the Initial Button in the view
fullfilment_btn.setVisibility(View.VISIBLE);//Displays the confirm Button
fullfilment_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
});
So here in this part of the code i get error while iterating the child elements .
Any help will be greatfull
I Solved this issue by a for loop, which will add the child to the new "mOpenOrderSelected" variable:
if (objOpenOrders.isChecked()) {
isSelectedOrderNumber++;
sb.append(objOpenOrders.getOrderID());
sb.append(",");
final OpenOrders parent = new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName());
ArrayList<Child> mOpenOrderItems=objOpenOrders.getChildren();
parent.setChildren(new ArrayList<Child>());
for(int k=0; k<mOpenOrderItems.size(); k++){
final Child child = (Child) mOpenOrderItems.get(k);
Log.d("ChildItemsname", "ChildItemsname:"+child.getName());
parent.getChildren().add(child);
}
mOpenOrdersSelected.add(parent);
}
So the new button click code will be like this:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mAdapter != null) {
int isSelectedOrderNumber=0;//This Variable will check with the parameter passed from server
mOpenOrdersSelected = new ArrayList<OpenOrders>();
StringBuffer sb = new StringBuffer();
Iterator<OpenOrders> it = mOpenOrders.iterator();
while(it.hasNext())
{
OpenOrders objOpenOrders = it.next();
//Do something with objOpenOrders
if (objOpenOrders.isChecked()) {
isSelectedOrderNumber++;
sb.append(objOpenOrders.getOrderID());
sb.append(",");
final OpenOrders parent = new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName());
ArrayList<Child> mOpenOrderItems=objOpenOrders.getChildren();
parent.setChildren(new ArrayList<Child>());
for(int k=0; k<mOpenOrderItems.size(); k++){
final Child child = (Child) mOpenOrderItems.get(k);
Log.d("ChildItemsname", "ChildItemsname:"+child.getName());
parent.getChildren().add(child);
}
mOpenOrdersSelected.add(parent);
}
}
//Below Condition Will Check the selected Items With parameter passed "mMAX_ORDERS_TOBEPICKED"
if(isSelectedOrderNumber<1){
ShowErrorDialog("Please Select atleast One order");
return;
}
if(isSelectedOrderNumber>mMAX_ORDERS_TOBEPICKED){
ShowErrorDialog(" Select Maximum of "+mMAX_ORDERS_TOBEPICKED+ " Orders only to process");
return;
}
//Below code is to Call again the adapter and Displays the Order's which are checked/selected.
expListView = (ExpandableListView) findViewById(R.id.expandable_order_item_list);
ExpandableOrderSelectedListAdapter mOrderSelectedAdapter = new ExpandableOrderSelectedListAdapter(SelectLocationActivity.this,mOpenOrdersSelected);
expListView.setAdapter(mOrderSelectedAdapter);
expListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//nothing to do , as Null Pointer exception Occurred ,to avoid that I just used this "setOnItemClickListener"
}
});
button.setVisibility(View.GONE);//Hide the Initial Button in the view
fullfilment_btn.setVisibility(View.VISIBLE);//Displays the confirm Button
fullfilment_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
});

Categories