I need to get the ID of room by its name from JSONObject.
I uploaded Json file here: https://gitlab.com/JaroslavVond/json/blob/master/Json
So I know the name of the room (Kitchen1) and I need to write some function in Java that will return me the ID of the room (in this case "1").
Any ideas how to do that?
So far I have something like this:
private static String GetIdRoom(String room) {
String id = "";
JSONObject myResponse = SendHTTP("/groups", "GET", "");
try {
// some code to get ID of room
} catch (Exception ex) {
System.out.println("error - " + ex);
}
return null ;
}
Iterator<?> ids = myResponse.keys();
while( ids.hasNext() ) {
id = (String) ids.next();
if(myResponse.getJSONObject(id).getString("name").equals(room)){
return id;
}
}
Related
Please help me, i get this errors when i run my app use Idea
here is screen of error
http://prntscr.com/en3lcu
here is part of code where create table
private String getTableDDL(final Class<? extends GlassContract.Table> table) {
return getTableDDL(table, GlassContract.getTableName(table));
}
private String getTableDDL(final Class<? extends GlassContract.Table> table, String tableName) {
final StringBuilder sql = new StringBuilder(128);
sql.append("create table ").append(tableName).append(" (");
for (final Field field : table.getFields()) {
if (field.getName().startsWith("_") || field.isAnnotationPresent(Deprecated.class))
continue;
try {
sql.append(field.get(null));
} catch (Exception ignore) {
}
try {
final Field type = table.getDeclaredField("_SQL_" + field.getName() + "_TYPE");
sql.append(' ').append(type.get(null));
} catch (Exception ignore) {
sql.append(" TEXT");
}
sql.append(',');
}
try {
final Field type = table.getDeclaredField("_PK_COMPOSITE");
sql.append("PRIMARY KEY(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
try {
final Field type = table.getDeclaredField("_UNIQUE_COMPOSITE");
sql.append("UNIQUE(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
sql.setLength(sql.length() - 1); // chop off last comma
sql.append(')');
Log.v(TAG, "DDL for " + table.getSimpleName() + ": " + sql);
return sql.toString();
}
I please help me, because I break my head))
Are you really trying to create text fields in your table that are named null?
Even if this works (and I am not sure it does), you are duplicating this and creating two identically named fields called null
The first field in that CREATE TABLE statement doesn't have a proper name (it is "null"). That's why it blows up.
There's more fields with illegal names as well.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to parse URL to get JSON response and particular values from that response. I dont have a sample code. Please give me a simple solution.
Below I have posted my URL and Response. I want to GET "School", Name" and Result values.
http://sample.com/login/username/ <username> /password <password>?
{
"response":{
"School":"SBOA",
"Name":"Anitha",
"Class":"Tenth",
},
"Result":"Good",
}
My Code :
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView output = (TextView) findViewById(R.id.textView1);
String strJson="URL";
String data = "";
System.out.println(strJson);
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("response");
System.out.println(jsonRootObject);
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
// int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("School").toString();
// float salary = Float.parseFloat(jsonObject.optString("salary").toString());
// data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";*/
}
//output.setText(data);
} catch (JSONException e) {e.printStackTrace();}
}
}
To read exactly that JSON, use this:
/** Verify that your strJson string contains this:
* {
* "response":{
* "School":"SBOA",
* "Name":"Anitha",
* "Class":"Tenth",
* },
* "Result":"Good",
* }
*/
String strJson = ??;
Log.d("TAG", "strJson: " + strJson);
try {
JSONObject jsonRootObject = new JSONObject(strJson);
JSONObject response = jsonRootObject.getJsonObject("response");
String schoolString = response.getString("School");
String nameString = response.getString("Name");
String classString = response.getString("Class");
String result = jsonRootObject.getString("Result");
} catch(JSONException e) {
Log.e("TAG", "Error reading json: " + jsonRootObject.toString());
}
If you have a JSONObject named json then follow this for getting school value
try{
jsonRootObject .getJSONObject("response").getString("School");
}catch(JSONException e)
{
e.printStackTrace();
}
The green is the lore
and the yellow is the displayname
http://puu.sh/k2iI7/62619f9536.jpg
I'm trying to seperate them in there rightful places for some odd reason there both appearing in both of the places.
items.java
public ItemStack applyLore(ItemStack stack, String name, String lore1){
ItemMeta meta = stack.getItemMeta();
meta.setDisplayName(name.replaceAll("&([0-9a-f])", "\u00A7$1"));
ArrayList<String> lore = new ArrayList<String>();
lore.add(lore1.replaceAll("&([0-9a-f])", "\u00A7$1"));
meta.setLore(lore);
stack.setItemMeta(meta);
return stack;
}
// p.getInventory().addItem(new ItemStack(Integer.parseInt(s), 1));
public void giveItemfromConfig(Player p)
{
String name ="name:";
String lore ="lore:";
for ( String s : plugin.file.getFile().getStringList(plugin.file.path) ) {
try {
s.split(" ");
if ( s.contains(name) || s.contains(lore) )
{
String namelength = s.substring(name.length());
String lorelength = s.substring(lore.length());
p.getInventory().addItem(applyLore(new ItemStack(Integer.parseInt(s.split(" ")[0])),
namelength.replace("_", " ").replace("ame:", "").replace("e:", "").replace("lor", "").replace("ore", ""),
lorelength.replace("_", " ").replace("lor:", "").replace("e:", "").replace("am", "").replace("lor", "").replace("ore", "")));
p.sendMessage("debug");
} else {
///nope.exe
p.getInventory().addItem(new ItemStack(Integer.parseInt(s)));
}
} catch(Exception e)
{
e.printStackTrace();
Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "Error in Config, Your id must be a integer ERROR:" + e);
}
}
}
config.yml
ChestPopulater:
items:
- 276 name:cookie
First thing is the problem is because of "Integer.parseInt(s)".
I dont know why you added this one as we dont have full source code or idea what you are trying to do with String "s" so that you will get result.
If you are doing it to get "276" , I will suggest you to do following :
String s2 = s.replaceAll("[A-Za-z]","").replace(":","").trim();
Integer i = Integer.parseInt(s2);
This problem really has me scratching my head.
I have a chat application that parses xml from the server. It is successful parsing the message text, msg id, but I am getting a nullpointerException for the UserID but I am pulling it from the same location. Please help
// Get messages
NodeList messageList = documentElement.getElementsByTagName("MESSAGE");
ret.messages = new ChatStruct[messageList.getLength()];
Log.v("response","Message Length " + messageList.getLength());
for (int i = 0; i < messageList.getLength(); i++) {
Element messageNode = (Element) messageList.item(i);
ret.messages[i] = new ChatStruct();
// Get messageId
try {
Element messageIdNode = (Element) messageNode.getElementsByTagName("ID").item(0);
String messageId = messageIdNode.getFirstChild().getNodeValue();
System.out.println("messageId = " + messageId);
ret.messages[i].id = Long.parseLong(messageId);
//Log.v("Util","Message ID " + Long.parseLong(messageId));
} catch (Exception e) {
ret.messages[i].id = 0l;
// e.printStackTrace();
}
// Get text
try {
Element textNode = (Element) messageNode.getElementsByTagName("TEXT").item(0);
String text = textNode.getFirstChild().getNodeValue();
System.out.println("text = " + text);
ret.messages[i].textMessage = text.trim();
//Log.v("Util","Message text " + text.trim());
} catch (Exception e) {
ret.messages[i].textMessage = "";
// e.printStackTrace();
}
// Get userId
try {
//ret.messages[i].userId = 1;
//Log.v("Util # userID node","userID should be 1");
Element userIdNode = (Element) messageNode.getElementsByTagName("USERID").item(0);
Log.i("Util # userID node","userIdNode set");
String userId = userIdNode.getFirstChild().getNodeValue();
//String userId = "1";
Log.i("Util # userID node","userId String set");
System.out.println("userId = " + userId);
ret.messages[i].userId = Long.parseLong(userId);
//ret.messages[i].userId = 1;
} catch (Exception e) {
Log.v("Util # userID node", "there was an error " + e);
ret.messages[i].userId = 0l;
// e.printStackTrace();
}
I can hard code the string and it works but other than that the error occurs at
String userId = userIdNode.getFirstChild().getNodeValue();
It makes it up to commented line of code confirming the userIDNode is set
I can't figure out why userID is not coming in from the server here is the XML:
<MESSAGE>
<ID><?php echo $row_shouts['msgid']; ?></ID>
<USERID><?php echo $row_shouts['userid']; ?></USERID>
<GENDER><?php echo $row_shouts['gender']; ?></GENDER>
<ONLINE><?php echo $row_shouts['account_status'];?></ONLINE>
<TDATE><?php echo datee("h:i:s M, d Y", strtotime($row_shouts['date'])); ?></TDATE>
<ICONID><?php echo $iconid; ?></ICONID>
<PIC><?php echo $PIC; ?></PIC>
<MSGPIC><?php echo $row_shouts['media']; ?></MSGPIC>
<PICDATE><?php echo strtotime($row_shouts['picdate']); ?></PICDATE>
<ALIAS><![CDATA[<?php echo $row_shouts['nickname'];?>]]></ALIAS>
<TEXT><![CDATA[<?php echo $mesg;?>]]></TEXT>
</MESSAGE>
Did you check with the DTD file for the supplied Xml, May be USERID is not clearly defined there.
[please share the error logs]
What's the execption say if you print the stack trace? It might be because the user id isn't a long and you're trying to parse it. I don't see any errors in the retrieval of the user id.
here is the code
private ResultSet rsResult;
try
{
rsResult = DBProcess.statement.executeQuery("SELECT * FROM patients");
}//end try
catch (SQLException ex)
{
out.println("<I>exception</I><br>");
Logger.getLogger(cUserLogin.class.getName()).log(Level.SEVERE, null, ex);
}//end catch
while (rsResult.next())
{
BigDecimal bdPatientID = rsResult.getBigDecimal("patient_id");
String strFirstname = rsResult.getString("first_name");
String strLastname = rsResult.getString("last_name");
String strMiddlename = rsResult.getString("middle_name");
String strGeneder = rsResult.getString("gender");
String strMeritalStatus = rsResult.getString("marital_status");
BigDecimal bdPhoneNo = rsResult.getBigDecimal("phone_no");
String strAddress = rsResult.getString("address");
String strDOB = rsResult.getDate("birth_dt").toString();
String strDOE = rsResult.getDate("dt_of_exam").toString();
}
i am not able to read records that are present after a recode which holds the null DATE field what can i do to get raid of this....
If rsResult.getDate("birth_dt") returns null, than calling toString() would cause a NullPointerException
You could rewrite this as:
String strDOB = rsResult.getDate("birth_dt") == null ? "" : rsResult.getDate("birth_dt").toString();