Appwarp Android Programming get Property from Room List Activity - android

I'm new in Multiplayer programming. How to set String into hashmap value ? I want to call hashmap properties from RoomListActivity and set it's value on QuizMaintain activity and also I want to set hashmap value from QuizMaintain class to textview. Here's my sample code
RoomListActivity
public void onJoinNewRoomClicked(View view){
progressDialog = ProgressDialog.show(this,"","Please wait...");
progressDialog.setCancelable(true);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("timer", "");
properties.put("question", "");
properties.put("answer", "");
properties.put("foulanswer", "");
theClient.createRoom(""+System.currentTimeMillis(), "Yoshua", 2, properties);
}
Then I want to set it's value from QuizMaintain activity
public class QuizMaintain extends Activity implements RoomRequestListener, NotifyListener {
private WarpClient theClient;
private HashMap<String, Object> properties;
private TextView txttimer,txtquestion;
private String roomId = "";
private HashMap<String, User> userMap = new HashMap<String, User>();
String string="5x5#5x4#150:3#500:20#536+59";
String[] questions = string.split("#");
String question1 = questions[0];
String question2 = questions[1];
String question3 = questions[2];
String question4 = questions[3];
String question5 = questions[4];
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_maintain);
txttimer = (TextView)findViewById(R.id.timer);
txtquestion = (TextView)findViewById(R.id.questionview);
try{
theClient = WarpClient.getInstance();
}catch(Exception e){
e.printStackTrace();
}
theClient.getLiveRoomInfo("143680827");
Intent intent = getIntent();
roomId = intent.getStringExtra("roomId");
init(roomId);
//setquestionview();
}
private void init(String roomId){
if(theClient!=null){
theClient.addRoomRequestListener(this);
theClient.addNotificationListener(this);
theClient.joinRoom(roomId);
}
}
#Override
public void onGetLiveRoomInfoDone(LiveRoomInfoEvent event) {
properties = event.getProperties();
properties.put("question", question1);
}
I want to set hashmap value where is the key are "question". And the value that i want to set are from split string.When I ask their support team if I want to get room properties I should call getLiveRoomInfo method and pass roomID as argument. A bit confused here. Thanks.
But it seems my problem are not solved yet. After call method updateRoomProperties but I got another error here. It's say WarpClient.AddZoneRequestListener(this) return null pointer exception

When you are creating a room you are passing a hashmap. This hashmap is stored as a JSON document inside the room on server. AppWarp calls it Room Properties.
Now to retrieve these properties you have to call getLiveRoomInfo method. This will present you the room properties. Here you are adding/changing some key-value again. But you haven't told the server that you are updating these room properties. Therefore your changes remain local and that too limited to the scope of function.
So, when you call the getLiveRoomInfo method, you won't see the changes as you haven't updated them on server. To update on server, you need to call updateRoomProperties method. In this method you can add or change your hashmap.

Related

Storing data to firebase from android client

Hello i'm a newbie on firebase, i'm creating a simple app to store text data on my firebase database. My goal is just to store the text but it seems that i cannot store the text.
I have this code for my send button which gets the value from the textbox and send it to the database. I can't figure out what's wrong.
public void onSendButtonClick(View v) {
String message = mMessageEdit.getText().toString();
Map<String, String> values = new HashMap<>();
values.put("name", "puf");
values.put("message", message.toString());
mFirebaseRef.push().setValue(values);
mMessageEdit.setText("");
}
Hope you could help me with this simple newbie problem.
Thanks. :)
I usually make a long variable to save date in millisecond.
long currentTimeInMillis = System.currentTimeInMillis();
Map<String, String> values = new HashMap<>();
values.put("date", currentTimeInMillis);
mFirebaseRef.push().setValue(values);
And then to convert it back I use DateFormat class (from android.text.format)
public static String getDate(String dateFormat, long currentTimeInMillis) {
return DateFormat.format(dateFormat, currentTimeInMillis); }
// Example usage
getDate("dd/MM/yyyy hh:mm:ss", "38232213325");
Try using a Map of type Map<String, Object> to write your values:
public void onSendButtonClick(View v) {
String message = mMessageEdit.getText().toString();
Map<String, Object> values = new HashMap<>();
values.put("name", "puf");
values.put("message", message);
mFirebaseRef.push().setValue(values);
mMessageEdit.setText("");
}

Select data from table in Kumulos

I am new to Kumulos development.
I want to get selected data from table of kumulos.
Like If user enter username and password i check from table that data exits or not.
But the issue is while checking data inserted in table and not giving me correct output.
While testing api in browser it works fine.
My code for select from table is below.
public void CallApiLogin(){
final String Uname=editUname.getText().toString();
final String pass=editPass.getText().toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", Uname);
params.put("password",pass);
Kumulos.call("user_register", params, new ResponseHandler() {
#Override
public void didCompleteWithResult(Object result) {
// Do updates to UI/data models based on result
ArrayList<LinkedHashMap<String, Object>> objects = (ArrayList<LinkedHashMap<String,Object>>) result;
for (LinkedHashMap<String, Object> item : objects) {
String name = (String) item.get("name");
String password = (String) item.get("password");
if(name.equalsIgnoreCase(Uname) && password.equalsIgnoreCase(pass)){
Intent i=new Intent(Login.this,Home.class);
startActivity(i);
}else{
Toast.makeText(getApplicationContext(),"Please enter valid username and password.",Toast.LENGTH_SHORT).show();
}
}
}
});
}
Please suggest where i am going wrong as requested data inserted in table.
But i want that request data exist or not????
After spending hours, I got solution.
Issue is creating api. In Kumulos you have to create different api.
I was using api "user_register", Now i have create other api call "Select_user".
This api works fine what the result i want.
I hope this question may help some other.

Parsing JSON then adding multiple strings to an ArrayList

Currently working on an app that takes results from a search, parses the JSON object returned, and then adds the resulting pieces into a few ArrayLists within a class created called VenueList.
Here is the method that receives the results from the service and parses the JSON:
private static List<String> getResultsFromJson(String json) {
ArrayList<String> resultList = new ArrayList<String>();
try {
JSONObject resultsWrapper = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = resultsWrapper.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
resultList.add(result.getString("text"));
}
}
catch (JSONException e) {
Log.e(TAG, "Failed to parse JSON.", e);
}
return resultList;
}
What results of this becomes a List variable call mResults (to clarify: mResults = getResultsFromJson(restResult);. That is then used, among other places, in the following loop that puts the results into an ArrayAdapter that is used for displaying them in a ListFragment:
for (String result : mResults) {
VenueList.addVenue(result, "HELLO WORLD");
adapter.add(result);
}
I also add the result to a class called VenueList that manages the results and makes them accessible for multiple views. It essentially just holds multiple ArrayLists that hold different types of details for each venue returned in the search. The method I use to add a venue to VenueList is below (and you can see it used in the for loop above):
public static void addVenue(String name, String geo) {
venueNames.add(name);
venueGeos.add(geo);
}
I want the addVenue method to be able to take multiple arguments and update the VenueList class. Yet, when I call the addVenue method in the for loop, I can only pass it String result (from the parameters of the loop) and can't figure out how to pass it a second argument (which should also come from the JSON parsed by getResultsFromJson) so I've used "HELLO WORLD" as a placeholder for now.
I realize getResultsFromJson only has one list returned. I need to be able to take multiple elements from the JSON object that I parse, and then add them to VenueList in the right order.
So my questions are:
1) Given the getResultsFromJson method and the for loop, how can I use the addVenue() method as designed? How do I parse multiple elements from the JSON, and then add them to the VenueList at the same time? I plan on adding more arguments to it later on, but I assume if I can make it work with two, I can make it work with four or five.
2) If that's not possible, how should the getResultsFromJson, the for loop, and the addVenue method be redesigned to work properly together?
Please let me know if you need more detail or code - happy to provide. Thank you!
EDIT - Full VenueList class:
public class VenueList {
private static ArrayList<String> venueNames;
private static ArrayList<String> venueGeos;
public VenueList() {
venueNames = new ArrayList<String>();
venueGeos = new ArrayList<String>();
}
public static void addVenue(String name, String geo) {
venueNames.add(name);
venueGeos.add(geo);
}
public static String getVenueName(int position) {
return venueNames.get(position);
}
public static String getVenueGeo(int position) {
return venueGeos.get(position);
}
public static void clearList() {
venueNames.clear();
venueGeos.clear();
}
}
Clarification: I will have additional ArrayLists for each element of data that I want to store about a venue (phone number, address, etc etc)
1) I don't think methods getResultsFromJson(String json) and addVenue(String name, String geo) fit your needs.
2) I would consider rewriting method getResultsFromJson(String json) to something like this:
private static SortedMap<Integer, List<String>> getResultsFromJson(String json) {
Map<Integer, String> resultMap = new TreeMap<Integer, String>();
//...
return resultMap;
}
where the number of keys of your map should be equal to the number of objects you're extracting info, and each one of them will properly have their own list of items just in the right order you extract them.
With this approach you can certainly change your logic to something like this:
// grab your retuned map and get an entrySet, the just iterate trough it
SortedMap<Integer, String> result = returnedMap.entrySet();
for (Entry<Integer, String> result : entrySet) {
Integer key = result.getKey(); // use it if you need it
List<String> yourDesiredItems = result.getValue(); // explicitly shown to know how to get it
VenueList.addVenue(yourDesiredItems);
}
public static void addVenue(List<String> yourDesiredItems) {
// refactor here to iterate the items trough the list and save properly
//....
}
EDIT -- as you wish to avoid the go-between map i'm assuming you need nothing to return from the method
First i'm providing you with a solution to your requirements, then i'll provide you with some tips cause i see some things that could smplify your design.
To save VenueList things directly from getResultsFromJSON do something like this:
private static void getResultsFromJson(String json) {
try {
JSONObject resultsWrapper = (JSONObject) new JSONTokener(json).nextValue();
JSONArray results = resultsWrapper.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
//FOR EXAMPLE HERE IS WHERE YOU NEED TO EXTRACT INFO
String name = result.getString("name");
String geo = result.getString("geo");
// and then...
VenueList.addVenue(name, geo, ..., etc);
}
} catch (JSONException e) {
Log.e(TAG, "Failed to parse JSON.", e);
}
}
This implies that your addVenue method should know receive all params needed; as you can see this is just a way (that you can consider a workaround to your needs), however as i don't know all requirements that lead you to code this model, i will point to a few things you might consider:
1. If there's a reason for VenueList class to use everything static, consider doing this:
static{
venueNames = new ArrayList<String>();
venueGeos = new ArrayList<String>();
//....
}
private VenueList(){
}
This way you won't need to get an instance every time and also will avoid null pointer exceptions when doing VenueList.addVenue(...) without previous instantiation.
2. Instead of having an ArrayList for every characteristic in VenueList class consider defining a model object for a Venue like this:
public class Venue{
String name;
String geo;
//... etc
public Venue(){
}
// ... getters & setters
}
then if you need that VenueList class you will just have a list o Venue objects (List<Venue>), this means that instead of calling the method addVenue, you will first create a brand new instance of Venue class and will call the setter method of each characteristic, as an example of the refactored for loop from the workaround i provided you you'd be using something like this:
List<Venue> myListOfVenues = new ArrayList<Venue>();
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
// THIS WOULD REMAIN THE SAME TO EXTRACT INFO
String name = result.getString("name");
String geo = result.getString("geo");
// and then instead of calling VenueList.addVenue(name, geo, ..., etc)...
Venue v = new Venue();
v.setName(name);
v.setGeo(geo);
// ...etc
myListOfVenues.add(v);
}
// Once you're done, set that List to VenueList class
VenueList.setVenueList(myListOfVenues);
So VenueList class would now have a single property List<Venue> venueList; and would suffer minor tweeks on methods getVenueName, etc... and everything would be more readable... i hope this helps you to get another approach to solve your problem, if i still don't make my point let me know and i'll try to help you out...

HashMap and ArrayList confusion in retrieval

I have a problem on arraylist and hashmap
As according to my requirement, I am storing the data into HashMap and after that I have created a List as List>.
HashMap<String,String> hashmap;
static List<HashMap<String,String>> hashmap_string;
And while retrieving the value from database and putting it on HashMap and ArrayList like:
contract_number=c.getString(c1);
Log.i("c1.getString,contract_number", contract_number);
String service_level=c.getString(c2);
hashmap=new HashMap<String, String>();
hashmap.put(contract_number, service_level);
hashmap_string.add(hashmap);
And now I want to retrieve the value as String,String
And when I am applying the code as:
for(int i=0;i<hashmap_string.size();i++)
{
Log.i("arraylist", ""+hashmap_string.get(i));
}
I am getting a single string value in the formet as
{Contract,ServiveValue}
but I want to split this into 2 string values...Also these values are redundant and if am using hashMap then it will not showing me the redundant value.
Please help me on this..
It seems you are missing something. When you execute hashmap_string.get(i), you will get the <HashMap<String,String>. So, This is the right value from code.
What you can do is :
HashMap<String, String> hashMap2 = hashmap_string.get(i);
String value = hashMap2.get("your_key");
Other way, you already have two splited string values. you can get that by using keySet() and values() methods over hashMap2 Object.
HashMap (and Maps in general) are used for multiple one-to-one mappings of keys and values. Are you sure you need that? Looking at your code it appears you're using the map as a "Pair" class. I would skip the list, and put everything in the same map, and then iterate over the pairs in the map:
// using tree map to have entries sorted on the key,
// rather than the key's hash value.
Map<String, String> data = new TreeMap<String, String>();
data.put("c1", "s1");
data.put("c2", "s2");
for (Map.Entry<String, String> entry : data.entrySet()) {
String contract = entry.getKey();
String level = entry.getValue();
Log.i("data", contract + " : " + level");
}
would output (assuming TreeSet):
c1 : s1
c2 : s2
Alternatively, create e.g. a ContractServiceLevel class that holds two strings (the contract number and the service level), and put instances of that class in your list.
EDIT:
public final class ContractServiceLevel {
public final String number;
public final String serviceLevel;
public ContractServiceLevel(String c, String s) {
number = c;
serviceLevel = s;
}
}
List<ContractServiceLevel> contracts = new ArrayList<ContractServiceLevel>();
contracts.add(new ContractServiceLevel("c1", "s1.1"));
contracts.add(new ContractServiceLevel("c1", "s1.2"));
contracts.add(new ContractServiceLevel("c2", "s2.1"));
for (ContractServiceLevel contract : contracts) {
Log.i("data", contract.number + ":" + contract.servicveLevel);
}
would output:
c1 : s1.1
c1 : s1.2
c2 : s2.1
String value = hashmap.get("contract");
u will be getting the value as ServiveValue

How to use Dictionary (like iphone NSDictionary) in android?

I have worked in soap message, and to parse the value from Webservice, the values are stored in ArrayList.
Example:
values are Employee name (Siva) and Employee id (3433fd), these two values are stored in arraylist, but I want to stored in Dictionary, How?
you can use HashMap like this
Map <String,String> map = new HashMap<String,String>();
//add items
map.put("3433fd","Siva");
//get items
String employeeName =(String) map.get("3433fd");
You can use Bundle.
as it offers String to various types of Mapping.
Bundle b = new Bundle();
b.putInt("identifier", 121);
b.putString("identifier", "Any String");
b.putStringArray("identifier", stringArray);
int i = b.getInt("identifier");
...
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText textview = (EditText) findViewById(R.id.editTextHash);
EditText textviewNew = (EditText) findViewById(R.id.editTextHash2);
Map<String, String> map = new HashMap<String,String>();
map.put("iOS", "100");
map.put("Android", "101");
map.put("Java", "102");
map.put(".Net", "103");
String TextString = "";
// Set<E> keys = map.keySet();
Set keys = map.keySet();
System.out.println("keys "+keys);
for (Iterator i = keys.iterator(); i.hasNext();)
{
String key = (String) i.next();
System.out.println("key "+key);
String value = (String) map.get(key);
System.out.println("value "+value);
textview.append(key + " = " + value);
TextString+=(key + " = " + value);
}
//textviewNew.setText(TextString);
// Iterator iterator = map.keySet().iterator();
//
// while (iterator.hasNext())
// {
// String object = (String) iterator.next();
// textview.setText(object);
// }
//
// //textview.setText(map.get("Siva"));
//
// System.out.println(map);
}
}
A Dictionary is an abstract class that maps keys to values and there is Dictionary Class in android refer link you can find a note at Class Overview
Do not use this class since it is obsolete. Please use the Map
interface for new implementations.
An attempt to insert either a null key or a null value to a dictionary will result to a NullPointerException,but you can use Map interface,it provides the exact same functionality of a dictionary.you can use it as bellow
//put values
Map Message = new HashMap();
Message.put("title", "Test message");
Message.put("description", "message description");
Message.put("email", "email#gmail.com");
//get values
Log.d("get Message","Message title -"+Message.get("title"));
you can also use A custom class as below
public class MessageObject {
String title;
String description;
String email;
}
you can use Getters and Setters to get and put values,not needed to remember the key names every time you may get some other advantages by this way.

Categories

Resources