How to set the ListObject in RecyclerView - java
I just started combining json data with recyclerView. After checking ArrayList can completed save key and value
public class test extends AppCompatActivity {
//set Attributes and storage List for json
public String jsonData = "myurl";
ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
...
private void loadingData() {//the method is called in onCreate
ProgressDialog dialog = ProgressDialog.show(this, "update",
"Loading Data", true);
//using Thread and Dialog while loading the data
new Thread(() -> {
try {
//use GetData(AsyncTask) & parse json
String jsonOpendata = new GetData().execute(jsonData).get();
JSONArray jsonArray = new JSONArray(jsonOpendata);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Set key & value for Hashmap
String Date = jsonObject.getString("date");
String[] dateFormat = Date.split("-");
switch (dateFormat[1]) {
case "1":
dateFormat[1] = "Jan.";
break;
case "2":
dateFormat[1] = "Feb.";
break;
case "3":
dateFormat[1] = "Mar.";
break;
case "4":
dateFormat[1] = "Apr.";
break;
case "5":
dateFormat[1] = "May.";
break;
case "6":
dateFormat[1] = "Jun.";
break;
case "7":
dateFormat[1] = "Jul.";
break;
case "8":
dateFormat[1] = "Aug.";
break;
case "9":
dateFormat[1] = "Sep.";
break;
case "10":
dateFormat[1] = "Oct.";
break;
case "11":
dateFormat[1] = "Nov.";
break;
case "12":
dateFormat[1] = "Dec.";
break;
}
String dateFormat = jsonObject.getString(String.valueOf(dateFormat)));
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("date", dateFormat);
...
arrayList.add(hashMap);
}
//loading completed Thread
runOnUiThread(() -> {
dialog.dismiss();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new GridLayoutManager(this,4));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter();
recyclerView.setAdapter(recyclerAdapter);
});
//catch....
And my recyclerView can read adapter and display the data successfully.
However, I found out the way more efficient and useful to save the data in arrayList is to put it into ListObject,so I've attempted it as follows
public class test extends AppCompatActivity {
//replacement
public String jsonData = "myurl";
**List<Book> bList = new ArrayList<>();**
...
private void loadingData() {//the method is called in onCreate
//using Thread and Dialog while loading the data
//use GetData(AsyncTask) & parse json
...
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Set key & value in Object
**Book book = new Book();**
String Date = jsonObject.getString("date");
String[] dateFormat = Date.split("-");
switch (dateFormat[1]) {
case "1":
dateFormat[1] = "Jan.";
break;
case "2":
dateFormat[1] = "Feb.";
break;
case "3":
dateFormat[1] = "Mar.";
break;
case "4":
dateFormat[1] = "Apr.";
break;
case "5":
dateFormat[1] = "May.";
break;
case "6":
dateFormat[1] = "Jun.";
break;
case "7":
dateFormat[1] = "Jul.";
break;
case "8":
dateFormat[1] = "Aug.";
break;
case "9":
dateFormat[1] = "Sep.";
break;
case "10":
dateFormat[1] = "Oct.";
break;
case "11":
dateFormat[1] = "Nov.";
break;
case "12":
dateFormat[1] = "Dec.";
break;
}
**astro.setDate(jsonObject.getString(String.valueOf(dateFormat)));**
...
**bList.add(book);**
}
//loading completed Thread
runOnUiThread(() -> {
dialog.dismiss();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new GridLayoutManager(this,4));
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(**this,bList**);
recyclerView.setAdapter(recyclerAdapter);
});
//catch....
Then add a Book class
public class Book {
String date;
public Book(String date) {
this.date = date;
}
public Book() {
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date= date;
}
And the errors occur said
W/System.err: org.json.JSONException: No value for [Ljava.lang.String;#1b3da99
I will really appreciate if someone could give me any solution or direction to solve this problem
I found the solution.The reason why the error tells
W/System.err: org.json.JSONException: No value for [Ljava.lang.String;#1b3da99
is because that I shouldn't get jsonObject data and transfer the formation at the same time.
book.setDate(jsonObject.getString(String.valueOf(dateFormat)));
the key of value was named 'date' in my json data.However, I thought it would be fine to run through the argument in dateformat and parse the value to string as an jsonObject value. jsonObject didn't have the key 'dateformat' ,so there was no clue can find my value.The ide can only find automatic-generated id in dateformat and transfer it to String #1b3da99 during the runtime.
the solution just seperate the procedure.
get the jsonObject in the main class
book.setDate(jsonObject.getString("date"));
bList.add(book)
and put the argument in the setDate.
public void setDate(String date) {//dateFormat argument}
Related
Switch while loop
I have a basic method that implements controlling of application menu using switch public void applicationMenu(String input) { switch (input) { case "1": findGroups(); break; case "2": findStudentsByCourseName(); break; case "3": addNewStudent(); break; case "4": deleteStudentById(); break; case "5": addStudentToCourse(); break; case "6": removeStudentCourse(); break; default: printDefault(); break; } } I use this method with a while loop to call my application menu public void callMenu() { boolean exit = false; while (!exit) { viewProvider.printMainMenu(); String input = viewProvider.readString(); if (input.equals("7")) { exit = true; } applicationMenu(input); } } How can I trigger exit from switch case but keep the structure of two methods at the same time?
This should work: public boolean applicationMenu(String input) { boolean shouldContinue = true; switch (input) { case "1": findGroups(); break; case "2": findStudentsByCourseName(); break; case "3": addNewStudent(); break; case "4": deleteStudentById(); break; case "5": addStudentToCourse(); break; case "6": removeStudentCourse(); break; case "7": shouldContinue = false; break; default: printDefault(); break; } return shouldContinue; } ... public void callMenu() { while (true) { viewProvider.printMainMenu(); String input = viewProvider.readString(); if (!applicationMenu(input)) { break; } } }
As stated in comments, you could throw an Exception, but I typically don't like to do that if i'm not in an actual error state. It makes more sense to me to use a return value and evaluate the result to determine if the program should terminate: public void callMenu() { boolean exit = false; while (!exit) { viewProvider.printMainMenu(); exit = applicationMenu(viewProvider.readString()); } } public boolean applicationMenu(String input) { switch (input) { case "1": findGroups(); return false; case "2": findStudentsByCourseName(); return false; case "3": addNewStudent(); return false; case "4": deleteStudentById(); return false; case "5": addStudentToCourse(); return false; case "6": removeStudentCourse(); return false; case "7": return true; default: printDefault(); } return false; }
Calling a method to return a different int from a switch
I'm trying to call a method and based on the input, return that value to a switch I have in another class. So if I were to choose the "1" element in my array, I would get reply returned as "4" back into my other class and make it run switch "4". In the other class I have the switch "4" set to another method. However, I keep getting the int value "1" returned from my method as it keeps calling that method (switch "1"). Which makes sense since it's the "1" element in my array, it should then run switch "1", but I thought that by setting "reply = 4", it would return an int "4" into my other class and thus invoke switch "4". How do I get my methods to return the value I want so I can put into my switch? Here's my first class where I'm doing the calling: package bunnyhunt; import javax.swing.ImageIcon; import javax.swing.JOptionPane; public class Messages { //Objects public Rooms roomCall = new Rooms(); //Instance Variables public static boolean gameOver = false; public static int roomNum; public static int reply; boolean visitedOtherRoom = false; //Constructors //Methods public void start() { //while loop while (gameOver == false) { //do-while loop do { String[] parkEntrance = {"Spring Meadow", "Aeryn's Overlook", "Garden Gate"}; reply = JOptionPane.showOptionDialog(null, "You're at the Park Entrance! What do you want to do?", "Bunny Adventure", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, parkEntrance, parkEntrance[0]); switch (reply) { case 0: System.out.println("oh man...Spring"); visitedOtherRoom = true; roomCall.springMeadow(); break; case 1: System.out.println("oh man...Aeryn"); visitedOtherRoom = true; roomCall.aerynsOverlook(); break; case 2: System.out.println("oh man...Garden"); visitedOtherRoom = true; roomCall.gardenGate(); break; default: System.out.println("error"); } } while (visitedOtherRoom == false); switch (reply) { case 0: System.out.println("second 0!!!"); visitedOtherRoom = true; roomCall.parkEntrance(); break; case 1: visitedOtherRoom = true; System.out.println("yes man!"); roomCall.aerynsOverlook(); break; case 2: visitedOtherRoom = true; roomCall.gardenGate(); break; case 3: visitedOtherRoom = true; roomCall.peacefulPond(); break; case 4: visitedOtherRoom = true; roomCall.readingNook(); break; default: System.out.println("default"); } } JOptionPane.showMessageDialog(null, "Game Over!!!"); } } and my second where the things I call reside: package bunnyhunt; import javax.swing.JOptionPane; public class Rooms { public static int reply; public int springMeadow() { String[] springMeadow = {"Park Entrance", "Reading Nook", "Search"}; Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Spring Meadow! What do you want to do?", "Spring Meadow", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, springMeadow, springMeadow[0]); switch (reply) { case 0: reply = 0; break; case 1: reply = 4; break; case 2: JOptionPane.showMessageDialog(null, "You searched!"); break; default: System.out.println("error"); } return reply; } public int aerynsOverlook() { String[] aerynsOverlook = {"Park Entrance", "Peaceful Pond", "Search"}; Messages.reply = JOptionPane.showOptionDialog(null, "You're in Aeryn's Overlook! What do you want to do?", "Aeryn's Overlook", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, aerynsOverlook, aerynsOverlook[0]); return reply; } public int gardenGate() { String[] gardenGate = {"Park Entrance", "Rose Gardent", "Butterfly Garden", "Flowering Forest"}; return reply; } public int readingNook() { String[] readingNook = {"Spring Meadow", "Search"}; Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Reading Nook! What do you want to do?", "Reading Nook", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, readingNook, readingNook[0]); return reply; } public int parkEntrance() { String[] parkEntrance = {"Spring Meadow", "Aeryn's Overlook", "Search"}; Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Park Entrance! What do you want to do?", "Park Entrance", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, parkEntrance, parkEntrance[0]); return reply; } public int peacefulPond() { String[] peacefulPond = {"Raven's Tower", "Aeryn's Overlook", "Search"}; Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Peaceful Pond! What do you want to do?", "Peaceful Pond", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, peacefulPond, peacefulPond[0]); return reply; } }
You are not returning a reply value from the start() method since this method is void AND switch statements inside don't return anything, despite they contain calls to appropriate methods like int aerynsOverlook(). You should modifystart` method like this: public int start() { ... switch (reply) { case 0: System.out.println("oh man...Spring"); visitedOtherRoom = true; return roomCall.springMeadow(); ... Secondly, I don't see how you are calling start() method to get its return value and use it in the second switch. Your MEssages class doesn't have any connection with the Rooms
Error Parsing XML response attributes with ksoap2 returns ClassCastException
I'm trying to figure out how to cast the response of the consume of a webservice, when casting the response envelope.bodyIn to my extended class object "BiometricConfigurationResponse" i'm getting this error: java.lang.ClassCastException: org.ksoap2.serialization.SoapObject cannot be cast to org.tempuri.BiometricConfigurationResponse The service is responding well and if i not cast it i get the dump right. Any ideas? This is what i'm doing: BiometricConfigurationResponse response= null; SoapObject obj = new SoapObject (wsNameSpace, methodName); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.implicitTypes = true; envelope.dotNet = true; envelope.setOutputSoapObject(obj); envelope.addMapping(wsNameSpace, "BiometricConfigurationResponse", new BiometricConfigurationResponse().getClass()); HttpTransportSE androidHttpTransport = new HttpTransportSE(wsURL); androidHttpTransport.debug = true; try { String soapAction=wsNameSpace + methodName; androidHttpTransport.call(soapAction, envelope); System.out.println(androidHttpTransport.requestDump); response = (BiometricConfigurationResponse)envelope.bodyIn; } catch (Exception e) { e.printStackTrace(); } And this is my custom class package org.tempuri; import java.util.Hashtable; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; public final class BiometricConfigurationResponse extends SoapObject { private int coderAlgorithm; private int templateFormat; private boolean juvenileMode; private int qualityThreshold; private boolean retryAcquisition; private boolean acceptBadQualityEnrollment; private boolean showQualityBar; private boolean showQualityThreshold; private int timeout; private int timeoutQualityCoder; private int enrollSecurityLevel; private boolean securityLevelCompatibility; private boolean liveImage; private java.lang.String setCulture; private int authenticationScore; public BiometricConfigurationResponse() { super("", ""); } public void setCoderAlgorithm(int coderAlgorithm) { this.coderAlgorithm = coderAlgorithm; } public int getCoderAlgorithm(int coderAlgorithm) { return this.coderAlgorithm; } public void setTemplateFormat(int templateFormat) { this.templateFormat = templateFormat; } public int getTemplateFormat(int templateFormat) { return this.templateFormat; } public void setJuvenileMode(boolean juvenileMode) { this.juvenileMode = juvenileMode; } public boolean getJuvenileMode(boolean juvenileMode) { return this.juvenileMode; } public void setQualityThreshold(int qualityThreshold) { this.qualityThreshold = qualityThreshold; } public int getQualityThreshold(int qualityThreshold) { return this.qualityThreshold; } public void setRetryAcquisition(boolean retryAcquisition) { this.retryAcquisition = retryAcquisition; } public boolean getRetryAcquisition(boolean retryAcquisition) { return this.retryAcquisition; } public void setAcceptBadQualityEnrollment(boolean acceptBadQualityEnrollment) { this.acceptBadQualityEnrollment = acceptBadQualityEnrollment; } public boolean getAcceptBadQualityEnrollment(boolean acceptBadQualityEnrollment) { return this.acceptBadQualityEnrollment; } public void setShowQualityBar(boolean showQualityBar) { this.showQualityBar = showQualityBar; } public boolean getShowQualityBar(boolean showQualityBar) { return this.showQualityBar; } public void setShowQualityThreshold(boolean showQualityThreshold) { this.showQualityThreshold = showQualityThreshold; } public boolean getShowQualityThreshold(boolean showQualityThreshold) { return this.showQualityThreshold; } public void setTimeout(int timeout) { this.timeout = timeout; } public int getTimeout(int timeout) { return this.timeout; } public void setTimeoutQualityCoder(int timeoutQualityCoder) { this.timeoutQualityCoder = timeoutQualityCoder; } public int getTimeoutQualityCoder(int timeoutQualityCoder) { return this.timeoutQualityCoder; } public void setEnrollSecurityLevel(int enrollSecurityLevel) { this.enrollSecurityLevel = enrollSecurityLevel; } public int getEnrollSecurityLevel(int enrollSecurityLevel) { return this.enrollSecurityLevel; } public void setSecurityLevelCompatibility(boolean securityLevelCompatibility) { this.securityLevelCompatibility = securityLevelCompatibility; } public boolean getSecurityLevelCompatibility(boolean securityLevelCompatibility) { return this.securityLevelCompatibility; } public void setLiveImage(boolean liveImage) { this.liveImage = liveImage; } public boolean getLiveImage(boolean liveImage) { return this.liveImage; } public void setSetCulture(java.lang.String setCulture) { this.setCulture = setCulture; } public java.lang.String getSetCulture(java.lang.String setCulture) { return this.setCulture; } public void setAuthenticationScore(int authenticationScore) { this.authenticationScore = authenticationScore; } public int getAuthenticationScore(int authenticationScore) { return this.authenticationScore; } public int getPropertyCount() { return 15; } public Object getProperty(int __index) { switch(__index) { case 0: return new Integer(coderAlgorithm); case 1: return new Integer(templateFormat); case 2: return new Boolean(juvenileMode); case 3: return new Integer(qualityThreshold); case 4: return new Boolean(retryAcquisition); case 5: return new Boolean(acceptBadQualityEnrollment); case 6: return new Boolean(showQualityBar); case 7: return new Boolean(showQualityThreshold); case 8: return new Integer(timeout); case 9: return new Integer(timeoutQualityCoder); case 10: return new Integer(enrollSecurityLevel); case 11: return new Boolean(securityLevelCompatibility); case 12: return new Boolean(liveImage); case 13: return setCulture; case 14: return new Integer(authenticationScore); } return null; } public void setProperty(int __index, Object __obj) { switch(__index) { case 0: coderAlgorithm = Integer.parseInt(__obj.toString()); break; case 1: templateFormat = Integer.parseInt(__obj.toString()); break; case 2: juvenileMode = "true".equals(__obj.toString()); break; case 3: qualityThreshold = Integer.parseInt(__obj.toString()); break; case 4: retryAcquisition = "true".equals(__obj.toString()); break; case 5: acceptBadQualityEnrollment = "true".equals(__obj.toString()); break; case 6: showQualityBar = "true".equals(__obj.toString()); break; case 7: showQualityThreshold = "true".equals(__obj.toString()); break; case 8: timeout = Integer.parseInt(__obj.toString()); break; case 9: timeoutQualityCoder = Integer.parseInt(__obj.toString()); break; case 10: enrollSecurityLevel = Integer.parseInt(__obj.toString()); break; case 11: securityLevelCompatibility = "true".equals(__obj.toString()); break; case 12: liveImage = "true".equals(__obj.toString()); break; case 13: setCulture = (java.lang.String) __obj; break; case 14: authenticationScore = Integer.parseInt(__obj.toString()); break; } } public void getPropertyInfo(int __index, Hashtable __table, PropertyInfo __info) { switch(__index) { case 0: __info.name = "coderAlgorithm"; __info.type = Integer.class; break; case 1: __info.name = "templateFormat"; __info.type = Integer.class; break; case 2: __info.name = "juvenileMode"; __info.type = Boolean.class; break; case 3: __info.name = "qualityThreshold"; __info.type = Integer.class; break; case 4: __info.name = "retryAcquisition"; __info.type = Boolean.class; break; case 5: __info.name = "acceptBadQualityEnrollment"; __info.type = Boolean.class; break; case 6: __info.name = "showQualityBar"; __info.type = Boolean.class; break; case 7: __info.name = "showQualityThreshold"; __info.type = Boolean.class; break; case 8: __info.name = "timeout"; __info.type = Integer.class; break; case 9: __info.name = "timeoutQualityCoder"; __info.type = Integer.class; break; case 10: __info.name = "enrollSecurityLevel"; __info.type = Integer.class; break; case 11: __info.name = "securityLevelCompatibility"; __info.type = Boolean.class; break; case 12: __info.name = "liveImage"; __info.type = Boolean.class; break; case 13: __info.name = "setCulture"; __info.type = java.lang.String.class; break; case 14: __info.name = "authenticationScore"; __info.type = Integer.class; break; } } }
After several days of research i understood that WSDL autogenerated code parse Properties but not Atrributes. So what i did was this: First i generate the stub code from my WSDL in this website: http://www.wsdl2code.com/pages/home.aspx My webservice name is "nutriment" son when you call it in MainActivity you have to do this: nutriment nws= new nutriment(); BiometricConfigurationResponse respuesta = nws.GetBiometricConfiguration(); Log.i(TAG, String.valueOf(respuesta.coderAlgorithm)); Log.i(TAG, String.valueOf(respuesta.templateFormat)); But it responses 0 in all cases because the WDSL stub files are parsing PROPERTIES NOT ATRIBUTES, so when you open the serialization generated file you'll got something like this: import org.ksoap2.serialization.KvmSerializable; import org.ksoap2.serialization.PropertyInfo; import java.util.Hashtable; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapPrimitive; public class BiometricConfigurationResponse implements KvmSerializable { public int coderAlgorithm; public int templateFormat; public BiometricConfigurationResponse(){} public BiometricConfigurationResponse(SoapObject soapObject) { if (soapObject == null) return; if (soapObject.hasProperty("coderAlgorithm")) { Object obj = soapObject.getProperty("coderAlgorithm"); if (obj != null && obj.getClass().equals(SoapObject.class)){ SoapPrimitive j =(SoapPrimitive) obj; coderAlgorithm = Integer.parseInt(j.toString()); } else if (obj!= null && obj instanceof Number){ coderAlgorithm = (Integer) obj; } } if (soapObject.hasProperty("templateFormat")) { Object obj = soapObject.getProperty("templateFormat"); if (obj != null && obj.getClass().equals(SoapPrimitive.class)){ SoapPrimitive j =(SoapPrimitive) obj; templateFormat = Integer.parseInt(j.toString()); }else if (obj!= null && obj instanceof Number){ templateFormat = (Integer) obj; } } } #Override public Object getProperty(int arg0) { switch(arg0){ case 0: return coderAlgorithm; case 1: return templateFormat; } return null; } #Override public int getPropertyCount() { return 15; } #Override public void getPropertyInfo(int index, #SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info) { switch(index){ case 0: info.type = PropertyInfo.INTEGER_CLASS; info.name = "coderAlgorithm"; break; case 1: info.type = PropertyInfo.INTEGER_CLASS; info.name = "templateFormat"; break; } #Override public void setProperty(int arg0, Object arg1) { } #Override public String getInnerText() { // TODO Auto-generated method stub return null; } #Override public void setInnerText(String arg0) { // TODO Auto-generated method stub } } The trick is to modify the parsing so instead of get the properties(e.g.): if (soapObject.hasProperty("coderAlgorithm")){ Object obj = soapObject.getProperty("coderAlgorithm"); if (obj != null && obj.getClass().equals(SoapObject.class)){ SoapPrimitive j =(SoapPrimitive) obj; coderAlgorithm = Integer.parseInt(j.toString()); } else if (obj!= null && obj instanceof Number){ coderAlgorithm = (Integer) obj; } } Get the ATTRIBUTES (e.g.): if (soapObject.hasAttribute("coderAlgorithm")) { Object obj = soapObject.getAttribute("coderAlgorithm"); if (obj != null && obj.getClass().equals(SoapObject.class)){ SoapPrimitive j =(SoapPrimitive) obj; coderAlgorithm = Integer.parseInt(j.toString()); } else if (obj!= null && obj instanceof Number){ coderAlgorithm = (Integer) obj; } else if (obj!= null && obj instanceof String){ coderAlgorithm = Integer.parseInt(obj.toString()); } }
Changing variable values from object fields
The following is my code: package com.collegeselector; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; public class CollegeList extends ListActivity { ArrayList<CollegeItem> collegeLists=new ArrayList<CollegeItem>(); ArrayList<String> nameList = new ArrayList<String>(); Comparator<CollegeItem> compare = new Comparator<CollegeItem>(){ public int compare(CollegeItem a, CollegeItem b){ return Double.compare(a.getScoreDistance(), b.getScoreDistance()); } }; CollegeItem michigan = new CollegeItem(3.79,30,2020,"University of Michigan","Ann Arbor, Michigan",true,false,true,false,true,true,true,true,true,true,true,true); CollegeItem berkeley = new CollegeItem(3.84,30,2040,"University of California Berkeley","Berkeley, California",false,false,true,true,true,true,true,true,true,true,true,true); CollegeItem stanford = new CollegeItem(3.96,33,2215,"Stanford University","Stanford, California",true,false,true,true,true,true,true,true,true,true,true,true); CollegeItem mit = new CollegeItem(3.92,33,2206,"Massachusetts Institute of Technology","Cambridge,Massachusetts",true,false,true,true,true,true,true,true,true,true,true,true); CollegeItem cit = new CollegeItem(3.95,34,2300,"California Institute of Technology","Pasadena,California",true,false,false,true,false,true,true,true,false,false,false,true); CollegeItem git = new CollegeItem(3.9,30,2010,"Georgia Institute of Technology","Atlanta,Georgia",true,false,true,true,true,true,true,false,true,true,true,true); CollegeItem uiuc = new CollegeItem(3.4,28,1975,"University of Illinois at Urbana-Champaign","Champaign,Illinois",true,true,false,false,true,true,true,true,true,false,true,true); CollegeItem carnegie = new CollegeItem(3.69,31,2100,"Carnegie Mellon University","Pittsburgh, Pennsylvania",false,false,false,false,false,true,true,false,true,false,true,false); CollegeItem cornell = new CollegeItem(3.87,31,2150,"Cornell Univeristy","Ithaca, New York",false,true,false,true,true,true,true,false,true,false,true,true); CollegeItem princeton = new CollegeItem(3.87,33,2260,"Princeton University","Princeton, New Jersey",true,false,false,true,false,false,false,false,false,false,false,false); CollegeItem purdue = new CollegeItem(3.7,27,1749,"Purdue University","West Lafayette, Indiana",true,true,false,false,true,false,true,false,false,true,false,true); CollegeItem utaustin = new CollegeItem(3.72,28,1854,"University of Texas at Austin","Austin, Texas",true,false,false,true,true,true,false,false,true,false,false,true); CollegeItem northwestern = new CollegeItem(3.8,32,2155,"Northwestern University","Evanston, Illinois",false,false,false,false,false,false,false,false,false,true,true,false); CollegeItem wisconsin = new CollegeItem(3.84,28,1905,"University of Wisconsin-Madison","Madison, Wisconsin",false,false,false,true,false,false,false,false,false,true,false,false); CollegeItem calpoly = new CollegeItem(3.87,28,1838,"California Polytechnic State University, San Luis Obispo","San Luis Obispo, California",false,false,false,false,false,false,false,false,false,false,false,false); CollegeItem johnshopkins = new CollegeItem(3.72,32,2103,"Johns Hopkins University","Baltimore, Maryland",false,false,true,false,false,false,false,false,true,false,false,false); CollegeItem pennstate = new CollegeItem(3.59,27,1778,"Pennsylvania State University-University Park","University Park, Pennsylvania",false,false,false,false,false,false,false,true,false,true,true,false); CollegeItem rice = new CollegeItem(3.87,32,2155,"Rice University","Houston, Texas",false,false,true,false,false,false,false,false,false,false,false,false); CollegeItem texasam = new CollegeItem(3.6,27,1755,"Texas A&M University","College Station, Texas",false,true,false,false,false,false,false,false,false,true,false,false); CollegeItem vtech = new CollegeItem(3.77,28,1823,"Virginia Tech","Blacksburg, Virginia",false,false,false,false,true,false,false,true,false,true,false,false); #Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); collegeLists.add(michigan);collegeLists.add(purdue); collegeLists.add(berkeley);collegeLists.add(utaustin); collegeLists.add(stanford);collegeLists.add(northwestern); collegeLists.add(mit);collegeLists.add(wisconsin); collegeLists.add(cit);collegeLists.add(calpoly); collegeLists.add(git);collegeLists.add(johnshopkins); collegeLists.add(uiuc);collegeLists.add(pennstate); collegeLists.add(carnegie);collegeLists.add(rice); collegeLists.add(cornell);collegeLists.add(texasam); collegeLists.add(princeton);collegeLists.add(vtech); Collections.sort(collegeLists, compare); for(CollegeItem collegeList : collegeLists){ nameList.add(collegeList.getName()); } setListAdapter(new ArrayAdapter<String>(CollegeList.this, android.R.layout.simple_list_item_1, nameList)); } private class CollegeItem { private double gpa; private int act; private int sat; private String name; private String location; private double score; private boolean match; private double scoreDistance; private boolean uaero, uagri, ubio, uchem, ucivil, ucomp, uelec, uphys, uenvi, uindus, umate, umech; public CollegeItem(double gpa, int act, int sat, String name, String location, boolean uaero, boolean uagri, boolean ubio, boolean uchem, boolean ucivil, boolean ucomp, boolean uelec, boolean uphys, boolean uenvi, boolean uindus, boolean umate, boolean umech){ this.gpa = gpa; this.act = act; this.sat = sat; this.name = name; this.location = location; this.uaero = uaero; this.uagri = uagri; this.ubio = ubio; this.uchem = uchem; this.ucivil = ucivil; this.ucomp = ucomp; this.uelec = uelec; this.uphys = uphys; this.uenvi = uenvi; this.uindus = uindus; this.umate = umate; this.umech = umech; if(act/36.0>sat/2400.0){ this.score = 0.6*gpa*25.0+0.4*(act/36.0)*100.0; }else{ this.score = 0.6*gpa*25.0+0.4*(sat/2400.0)*100.0; } scoreDistance = Math.abs(this.score-MainActivity.scoreDouble)/MainActivity.scoreDouble; if(uaero&&ListOfMajors.aerospace) match = true; if(uagri&&ListOfMajors.agricultural) match = true; if(ubio&&ListOfMajors.biomed) match = true; if(uchem&&ListOfMajors.chem) match = true; if(ucivil&&ListOfMajors.civil) match = true; if(ucomp&&ListOfMajors.computer) match = true; if(uelec&&ListOfMajors.electrical) match = true; if(uphys&&ListOfMajors.physics) match = true; if(uenvi&&ListOfMajors.environment) match = true; if(uindus&&ListOfMajors.industrial) match = true; if(umate&&ListOfMajors.materials) match = true; if(umech&&ListOfMajors.mechanical) match = true; } public String getName(){ return this.name; } public double getScoreDistance(){ return this.scoreDistance; } CheckList Activity public class ListOfMajors extends Activity { boolean[] mItemState; public static boolean aerospace, agricultural, biomed, chem, civil, computer, electrical, physics, environment, industrial, materials, mechanical; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.majorslist); ListView mylist = (ListView) findViewById(R.id.majorslist); final String[] list={"Aerospace Engineering","Agricultural Engineering", "Biomedical Engineering","Chemical Engineering","Civil Engineering", "Computer Engineering","Electrical Engineering","Engineering Physics", "Environmental Engineering","Industrial Engineering", "Materials Engineering","Mechanical Engineering"}; mItemState = new boolean[list.length]; ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListOfMajors.this,android.R.layout.simple_list_item_multiple_choice,list); mylist.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() { #Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Toggle the state mItemState[position] = !mItemState[position]; if (mItemState[position]) switch(position){ case 0: aerospace = true; case 1: agricultural = true; case 2: biomed = true; case 3: chem = true; case 4: civil = true; case 5: computer = true; case 6: electrical = true; case 7: physics = true; case 8: environment = true; case 9: industrial = true; case 10: materials = true; case 11: mechanical = true; } else{ switch(position){ case 0: aerospace = false; case 1: agricultural = false; case 2: biomed = false; case 3: chem = false; case 4: civil = false; case 5: computer = false; case 6: electrical = false; case 7: physics = false; case 8: environment = false; case 9: industrial = false; case 10: materials = false; case 11: mechanical = false; } } } }); mylist.setAdapter(adapter); } } The variables such as uaero and uagri are boolean fields of objects. I have a quite a few objects in this class. The variables such as ListOfMajors.aerospace and ListOfMajors.agricultural are boolean values from another class which are set to true if a checkbox is clicked. All of these pairs of variables correspond with each other and would like the variable match set to true if both of the other variables are true. As of right now, the code doesn't seem to working as match doesn't appear to be changing to true. What should I do to get this to work?
Your cases are probably not doing what you think .. since there is no break a case position 0 will set all of the variables to true (or false) switch(position){ case 0: aerospace = true; break; case 1: agricultural = true;break; case 2: biomed = true;break; case 3: chem = true;break; case 4: civil = true;break; case 5: computer = true;break; case 6: electrical = true;break; case 7: physics = true;break; case 8: environment = true;break; case 9: industrial = true;break; case 10: materials = true;break; case 11: mechanical = true; break; }
onchildclick case statement android
the project run ok,the case 3 child clicks ok ,but in case 2 clicks it display activity from case 3 or activity that I deleted it before then on return it display the activity that I wanted (when I click microbiology it display pedodontics then on return click it display Microbiology) import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ExpandableListView.OnGroupClickListener; import android.widget.ExpandableListView.OnGroupCollapseListener; import android.widget.ExpandableListView.OnGroupExpandListener; import android.widget.Toast; import com.freedental.blogspot.R; public class MainActivity extends Activity { ExpandableListAdapter listAdapter; ExpandableListView expListView; List<String> listDataHeader; HashMap<String, List<String>> listDataChild; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get the listview expListView = (ExpandableListView) findViewById(R.id.lvExp); // preparing list data prepareListData(); listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild); // setting list adapter expListView.setAdapter(listAdapter); // Listview Group click listener expListView.setOnGroupClickListener(new OnGroupClickListener() { #Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { // Toast.makeText(getApplicationContext(), // "Group Clicked " + listDataHeader.get(groupPosition), // Toast.LENGTH_SHORT).show(); return false; } }); // Listview Group expanded listener expListView.setOnGroupExpandListener(new OnGroupExpandListener() { #Override public void onGroupExpand(int groupPosition) { Toast.makeText(getApplicationContext(), listDataHeader.get(groupPosition) + " Expanded", Toast.LENGTH_SHORT).show(); } }); // Listview Group collasped listener expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() { #Override public void onGroupCollapse(int groupPosition) { Toast.makeText(getApplicationContext(), listDataHeader.get(groupPosition) + " Collapsed", Toast.LENGTH_SHORT).show(); } }); // Listview on child click listener expListView.setOnChildClickListener(new OnChildClickListener() { #Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { switch(groupPosition) { case 1: switch (childPosition) { case 0: Intent c1= new Intent(MainActivity.this,Webv1Activity.class); startActivity(c1); break; } case 2: switch (childPosition) { case 0: Intent d1= new Intent(MainActivity.this,Webv1Activity.class); startActivity(d1); break; case 1: Intent d2= new Intent(MainActivity.this,Webv2Activity.class); startActivity(d2); break; case 2: Intent d3= new Intent(MainActivity.this,Webv3Activity.class); startActivity(d3); break; case 3: Intent d4= new Intent(MainActivity.this,Webv4Activity.class); startActivity(d4); break; case 4: Intent d5= new Intent(MainActivity.this,Webv5Activity.class); startActivity(d5); break; case 5: Intent d6= new Intent(MainActivity.this,Webv6Activity.class); startActivity(d6); break; case 6: Intent d7= new Intent(MainActivity.this,Webv7Activity.class); startActivity(d7); break; case 7: Intent d8= new Intent(MainActivity.this,Webv8Activity.class); startActivity(d8); break; } case 3: switch (childPosition) { case 0: Intent a1= new Intent(MainActivity.this,Webv9Activity.class); startActivity(a1); break; case 1: Intent a2= new Intent(MainActivity.this,Webv10Activity.class); startActivity(a2); break; case 2: Intent a3= new Intent(MainActivity.this,Webv11Activity.class); startActivity(a3); break; case 3: Intent a4= new Intent(MainActivity.this,Webv12Activity.class); startActivity(a4); break; case 4: Intent a5= new Intent(MainActivity.this,Webv13Activity.class); startActivity(a5); break; case 5: Intent a6= new Intent(MainActivity.this,Webv14Activity.class); startActivity(a6); break; case 6: Intent a7= new Intent(MainActivity.this,Webv15Activity.class); startActivity(a7); break; case 7: Intent a8= new Intent(MainActivity.this,Webv16Activity.class); startActivity(a8); break; } } return false; } }); } /* * Preparing the list data */ private void prepareListData() { listDataHeader = new ArrayList<String>(); listDataChild = new HashMap<String, List<String>>(); // Adding child data listDataHeader.add("1st Grade lectures"); listDataHeader.add("2nd Grade lectures"); listDataHeader.add("3rd Grade lectures"); listDataHeader.add("4th Grade lectures"); listDataHeader.add("5th Grade lectures"); // Adding child data List<String> first = new ArrayList<String>(); first.add("Under Construction"); List<String> second = new ArrayList<String>(); second.add("Prosthodontics"); second.add("Other under con"); List<String> third = new ArrayList<String>(); third.add("Microbiology"); third.add("Pathology"); third.add("Pharmacology"); third.add("Surgery"); third.add("Operative"); third.add("Prosthodontics"); third.add("Radiology"); third.add("Cummunity"); List<String> fourth = new ArrayList<String>(); fourth.add("periodontology"); fourth.add("pedodontics"); fourth.add("Orthodontics"); fourth.add("Prosthodontics"); fourth.add("Oral Pathology"); fourth.add("Oral Surgery"); fourth.add("General Surgery"); fourth.add("General Medicine"); List<String> fifth = new ArrayList<String>(); fifth.add("Under Construction"); listDataChild.put(listDataHeader.get(0), first); // Header, Child data listDataChild.put(listDataHeader.get(1), second); listDataChild.put(listDataHeader.get(2), third); listDataChild.put(listDataHeader.get(3), fourth); listDataChild.put(listDataHeader.get(4), fifth); } }
You are missing a break statement after case 1 and case 2 : expListView.setOnChildClickListener(new OnChildClickListener() { #Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { switch(groupPosition) { case 1: switch (childPosition) { case 0: Intent c1= new Intent(MainActivity.this,Webv1Activity.class); startActivity(c1); break; } =======>>>>> break; case 2: switch (childPosition) { case 0: Intent d1= new Intent(MainActivity.this,Webv1Activity.class); startActivity(d1); break; case 1: Intent d2= new Intent(MainActivity.this,Webv2Activity.class); startActivity(d2); break; case 2: Intent d3= new Intent(MainActivity.this,Webv3Activity.class); startActivity(d3); break; case 3: Intent d4= new Intent(MainActivity.this,Webv4Activity.class); startActivity(d4); break; case 4: Intent d5= new Intent(MainActivity.this,Webv5Activity.class); startActivity(d5); break; case 5: Intent d6= new Intent(MainActivity.this,Webv6Activity.class); startActivity(d6); break; case 6: Intent d7= new Intent(MainActivity.this,Webv7Activity.class); startActivity(d7); break; case 7: Intent d8= new Intent(MainActivity.this,Webv8Activity.class); startActivity(d8); break; } ==========>>>>> break; case 3: switch (childPosition) { case 0: Intent a1= new Intent(MainActivity.this,Webv9Activity.class); startActivity(a1); break; case 1: Intent a2= new Intent(MainActivity.this,Webv10Activity.class); startActivity(a2); break; case 2: Intent a3= new Intent(MainActivity.this,Webv11Activity.class); startActivity(a3); break; case 3: Intent a4= new Intent(MainActivity.this,Webv12Activity.class); startActivity(a4); break; case 4: Intent a5= new Intent(MainActivity.this,Webv13Activity.class); startActivity(a5); break; case 5: Intent a6= new Intent(MainActivity.this,Webv14Activity.class); startActivity(a6); break; case 6: Intent a7= new Intent(MainActivity.this,Webv15Activity.class); startActivity(a7); break; case 7: Intent a8= new Intent(MainActivity.this,Webv16Activity.class); startActivity(a8); break; } } return false; } });