Display Json data in unity - json

I want to create scoreboard with Firebase in Unity.
I know how to access data but I have problem with displaying these on screen.
I tried to add user data to list but I'm not sure if this is a good idea or if this will actually work
Here is my code:
public class Scoresmulti : MonoBehaviour
{
//Zliczanie punktów i wyświetlanie wyniku
public static int pointssum = 0;
public Text points;
private string user;
public String scoresboard;
public Array Scores;
public List<USers> scores = new List<USers>();
USers users = new USers();
public static fsSerializer serializer = new fsSerializer();
void Start()
{
//Posttodb();
Debug.Log("wykonano");
Getdata();
}
private void getscore()
{
//display text
}
void Update()
{
points.text = "Poprawne odpowiedzi: " + pointssum;
}
private void Posttodb()
{ user = nazwagracza.Playernick;
if (user != null)
{
USers users = new USers();
RestClient.Put("https://quizgame-inz.firebaseio.com/names/" + user + ".json", users);
}
}
private void Getdata()
{
StringBuilder builder = new StringBuilder();
RestClient.Get("https://quizgame-inz.firebaseio.com/.json").Then(response =>
{
fsData userdata = fsJsonParser.Parse(response.Text);
USers[] users = null;
serializer.TryDeserialize(userdata, ref users);
foreach (var user in users)
{
scores.Add(user);
}
});
}
}

Related

Getting json data from Spoonacular in Android Studio

trying to get to an Android App random recipes from Spoonacular. For some reason, I'm not getting the data from the json. I know how to do this in Javascript, but that's no use to me in Java.
My repository file:
public class RecipeRepository {
private static final String API_KEY = "472f31ce4a5e4e5792ca9ab6d1833e51";
private static final String URL = "https://api.spoonacular.com/recipes/random?apiKey=%s";
private final Application application;
private final MutableLiveData<ArrayList<Recipe>> recipeLiveData;
private final ArrayList<Recipe> arrayList = new ArrayList<>();
public RecipeRepository(Application application) {
this.application = application;
recipeLiveData = new MutableLiveData<>();
}
public void getDayRecipe() {
Ion.with(application)
.load(String.format(URL,API_KEY)).asJsonObject()
.setCallback((e, result) -> {
Log.i( "getRandomRecipe",result.getAsJsonPrimitive().toString());
parseResults(result);
});
}
public String removeAbles(String text) {return text.substring(1,text.length()-1); }
private void parseResults(JsonObject result) {
JsonObject randomRecipe = (JsonObject) result.getAsJsonArray("recipes").get(0);
String title = String.valueOf(randomRecipe.get("title"));
String instructions = String.valueOf(randomRecipe.get("Instructions"));
//ingredients
//image
recipeLiveData.setValue(arrayList);
}
public MutableLiveData<ArrayList<Recipe>> getRecipeLiveData() {
return recipeLiveData;
}
}
I get a 'variable is never used' with title, instructions and removeAbles

D/Volley: [1] 5.onErrorResponse: Product

How do I insert data from MySQL into Gridview on Fragments? I've tried it with a coding method used for Activity. I've changed a lot but it's still wrong. This is my coding:
/**
* A simple {#link Fragment} subclass.
*/
public class Product extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
GridView grid_product;
SwipeRefreshLayout swipe;
List<ProductData> newsList = new ArrayList<ProductData>();
private static final String TAG = Product.class.getSimpleName();
private static String url_list = Server.URL + "news.php?offset=";
private int offSet = 0;
int no;
ProductAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
public Product() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
grid_product = (GridView) view.findViewById(R.id.grid_product);
setProduct();
return view;
}
private void setProduct(){
adapter = new ProductAdapter(getActivity(), newsList);
grid_product.setAdapter(adapter);
grid_product.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pindah activity
startActivity(new Intent(
getActivity(), DetailActivity.class
));
}
});
I don't know where the mistake is:
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
}
);
grid_product.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callNews(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
}
#Override
public void onRefresh() {
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
I don't know where the mistake is:
private void callNews(int page){
swipe.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ProductData news = new ProductData();
no = obj.getInt(TAG_NO);
news.addId(obj.getString(TAG_ID));
news.addJudul(obj.getString(TAG_JUDUL));
if (obj.getString(TAG_GAMBAR) != "") {
news.addGambar(obj.getString(TAG_GAMBAR));
}
news.addDatetime(obj.getString(TAG_TGL));
news.addIsi(obj.getString(TAG_ISI));
// adding news to news array
newsList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}

How to save content of list into OBJECT type

I have a list/tuple which I have populated with some values. I want to save these values into a variable of OBJECT type in script component. How can I achieve this. Till now I did tried this with no success.
public class ScriptMain : UserComponent
{
private List<SomeValues> SomeList = new List<SomeValues>();
public override void PreExecute()
{
base.PreExecute();
}
public override void PostExecute()
{
base.PostExecute();
//Object type variable in which I am trying to save list
Variables.LatestDateTime = SomeList;
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
var MatchingRow = SomeList.FirstOrDefault(d => d.Id == Row.Id);
if (MatchingRow == null)
{
SomeList.Add(new DateTimeValues
{
ID = Row.ID,
LatestDateTime = Row.DateTime
});
}
else
{
if (MatchingRow.LatestDateTime < Row.DateTime)
{
MatchingRow.LatestDateTime = Row.DateTime;
}
}
}
public class SomeValues
{
public int Id { get; set; }
public DateTime LatestDateTime { get; set; }
}
}
You need to write your list to a datatable first and then set your datatable to your variable..
Example - Fill datatable from list
List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
DataTable dt = new DataTable();
dt.Columns.Add("column1", typeof (string));
foreach (string str in cities)
{
DataRow row = dt.NewRow();
row["column1"] = str;
dt.Rows.Add(row);
}
Write your dattable to your object variable
Dts.Variables["User::NameList"].Value = dt;
And then you can use a foreach ado numerator to loop over your object variable in SSIS.

store details in windows phone 8 using sqlite?

I want to store information from the NFC tag I read and store in the database and show it all in another page but I am having problem in using implementing sqlite.I cant add the information to the database using sqlite.
Below is my checkin class from where I read from the NFC tag
public partial class Checkin : PhoneApplicationPage
{
private ProximityDevice _device;
private long _subscriptionIdNdef;
public static double Latitud_do { get; set; }
public static double Longtitude_do { get; set; }
public static string latitude { get; set; }
public static string longtitude { get; set; }
public static string Floor_st { get; set; }
public static string Zone_st { get; set; }
History store = new History();
public Checkin()
{
InitializeProximityDevice();
InitializeComponent();
}
private void SetLogStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (LogStatus != null) LogStatus.Text = newStatus; });
}
private void SetFloorStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (FloorStatus != null) FloorStatus.Text = newStatus; });
}
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
MessageBox.Show(" ");
}
private void InitializeProximityDevice()
{
_device = Windows.Networking.Proximity.ProximityDevice.GetDefault();
if (_device != null)
{
_subscriptionIdNdef = _device.SubscribeForMessage("NDEF", MessageReceivedHandler);
}
}
private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
{
var rawMsg = message.Data.ToArray();
var ndefMessage = NdefMessage.FromByteArray(rawMsg);
////// Loop over all records contained in the NDEF message
foreach (NdefRecord record in ndefMessage)
{
if (NdefTextRecord.IsRecordType(record))
{
// Convert and extract URI info
var textRecord = new NdefTextRecord(record);
string[] str = textRecord.Text.Split('|');
var Floor_st = str[0];
var Zone_st = str[1];
var latitude = str[2];
var longtitude = str[3];
Latitud_do = double.Parse(latitude);
Longtitude_do = double.Parse(longtitude);
SetLogStatus("Floor: " + Floor_st + " Zone: " + Zone_st );
SetFloorStatus("Longitude: " + latitude + " Longitude: " + longtitude);
//store.AddDb(Floor_st, Zone_st, Latitud_do, Longtitude_do);
}
}
}
}
Below here is the main dbhelper class for the main sqlite functions
public class DbHelper
{
SQLiteConnection dbConn;
public async Task<bool> onCreate(string DB_PATH)
{
try
{
if (!CheckFileExists(DB_PATH).Result)
{
using (dbConn = new SQLiteConnection(DB_PATH))
{
dbConn.CreateTable<historyTableSQlite>();
}
}
return true;
}
catch
{
return false;
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
return false;
}
}
//retrieve all list from the database
public ObservableCollection<historyTableSQlite> ReadHistory()
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
return HistoryList;
}
}
// Insert the new info in the histrorytablesqlite table.
public void Insert(historyTableSQlite newcontact)
{
using (var dbConn = new SQLiteConnection(App.DB_PATH))
{
dbConn.RunInTransaction(() =>
{
dbConn.Insert(newcontact);
});
}
}
}
below is the class from where I read all the information
public class ReadAllContactsList
{
DbHelper Db_Helper = new DbHelper();
public ObservableCollection<historyTableSQlite> GetAllHistory()
{
return Db_Helper.ReadHistory();
}
}
}
And last is the class where I want to show all the information I have stored
ublic partial class History : PhoneApplicationPage
{
// string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
public History()
{
InitializeComponent();
}
private void ReadHistoryList_Loaded(object sender, RoutedEventArgs e)
{
ReadAllContactsList dbhistory = new ReadAllContactsList();
DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();//Latest contact ID can Display first
}
public void AddInfo(object sender, RoutedEventArgs e)
{
DbHelper Db_helper = new DbHelper();
Db_helper.Insert(new historyTableSQlite(
));
}
}
I followed the following post but still struglling
http://bsubramanyamraju.blogspot.com/2014/08/windowsphone-8-sqlite-storing-data-in.html
Thank you for your help in advance

Casting an object using 'as' returns null: myObject = newObject as MyObject; // null

I am trying to create a custom object in AS3 to pass information to and from a server, which in this case will be Red5. In the below screenshots you will see that I am able to send a request for an object from as3, and receive it successfully from the java server. However, when I try to cast the received object to my defined objectType using 'as', it takes the value of null. It is my understanding that that when using "as" you're checking to see if your variable is a member of the specified data type. If the variable is not, then null will be returned.
This screenshot illustrates that I am have successfully received my object 'o' from red5 and I am just about to cast it to the (supposedly) identical datatype testObject of LobbyData:
Enlarge
However, when testObject = o as LobbyData; runs, it returns null. :(
Enlarge
Below you will see my specifications both on the java server and the as3 client. I am confident that both objects are identical in every way, but for some reason flash does not think so. I have been pulling my hair out for a long time, does anyone have any thoughts?
AS3 Object:
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;
import flash.net.registerClassAlias;
[Bindable]
[RemoteClass(alias = "myLobbyData.LobbyData")]
public class LobbyData implements IExternalizable
{
private var sent:int; // java sentinel
private var u:String; // red5 username
private var sen:int; // another sentinel?
private var ui:int; // fb uid
private var fn:String; // fb name
private var pic:String; // fb pic
private var inb:Boolean; // is in the table?
private var t:int; // table number
private var s:int; // seat number
public function setSent(sent:int):void
{
this.sent = sent;
}
public function getSent():int
{
return sent;
}
public function setU(u:String):void
{
this.u = u;
}
public function getU():String
{
return u;
}
public function setSen(sen:int):void
{
this.sen = sen;
}
public function getSen():int
{
return sen;
}
public function setUi(ui:int):void
{
this.ui = ui;
}
public function getUi():int
{
return ui;
}
public function setFn(fn:String):void
{
this.fn = fn;
}
public function getFn():String
{
return fn;
}
public function setPic(pic:String):void
{
this.pic = pic;
}
public function getPic():String
{
return pic;
}
public function setInb(inb:Boolean):void
{
this.inb = inb;
}
public function getInb():Boolean
{
return inb;
}
public function setT(t:int):void
{
this.t = t;
}
public function getT():int
{
return t;
}
public function setS(s:int):void
{
this.s = s;
}
public function getS():int
{
return s;
}
public function readExternal(input:IDataInput):void
{
sent = input.readInt();
u = input.readUTF();
sen = input.readInt();
ui = input.readInt();
fn = input.readUTF();
pic = input.readUTF();
inb = input.readBoolean();
t = input.readInt();
s = input.readInt();
}
public function writeExternal(output:IDataOutput):void
{
output.writeInt(sent);
output.writeUTF(u);
output.writeInt(sen);
output.writeInt(ui);
output.writeUTF(fn);
output.writeUTF(pic);
output.writeBoolean(inb);
output.writeInt(t);
output.writeInt(s);
}
}
Java Object:
package myLobbyData;
import org.red5.io.amf3.IDataInput;
import org.red5.io.amf3.IDataOutput;
import org.red5.io.amf3.IExternalizable;
public class LobbyData implements IExternalizable
{
private static final long serialVersionUID = 115280920;
private int sent; // java sentinel
private String u; // red5 username
private int sen; // another sentinel?
private int ui; // fb uid
private String fn; // fb name
private String pic; // fb pic
private Boolean inb; // is in the table?
private int t; // table number
private int s; // seat number
public void setSent(int sent)
{
this.sent = sent;
}
public int getSent()
{
return sent;
}
public void setU(String u)
{
this.u = u;
}
public String getU()
{
return u;
}
public void setSen(int sen)
{
this.sen = sen;
}
public int getSen()
{
return sen;
}
public void setUi(int ui)
{
this.ui = ui;
}
public int getUi()
{
return ui;
}
public void setFn(String fn)
{
this.fn = fn;
}
public String getFn()
{
return fn;
}
public void setPic(String pic)
{
this.pic = pic;
}
public String getPic()
{
return pic;
}
public void setInb(Boolean inb)
{
this.inb = inb;
}
public Boolean getInb()
{
return inb;
}
public void setT(int t)
{
this.t = t;
}
public int getT()
{
return t;
}
public void setS(int s)
{
this.s = s;
}
public int getS()
{
return s;
}
#Override
public void readExternal(IDataInput input)
{
sent = input.readInt();
u = input.readUTF();
sen = input.readInt();
ui = input.readInt();
fn = input.readUTF();
pic = input.readUTF();
inb = input.readBoolean();
t = input.readInt();
s = input.readInt();
}
#Override
public void writeExternal(IDataOutput output)
{
output.writeInt(sent);
output.writeUTF(u);
output.writeInt(sen);
output.writeInt(ui);
output.writeUTF(fn);
output.writeUTF(pic);
output.writeBoolean(inb);
output.writeInt(t);
output.writeInt(s);
}
}
AS3 Client:
public function refreshRoom(event:Event)
{
var resp:Responder=new Responder(handleResp,null);
ncLobby.call("getLobbyData", resp, null);
}
public function handleResp(o:Object):void
{
var testObject:LobbyData=new LobbyData;
testObject = o as LobbyData;
trace(testObject);
}
Java Client
public LobbyData getLobbyData(String param)
{
LobbyData lobbyData1 = new LobbyData();
lobbyData1.setSent(5);
lobbyData1.setU("lawlcats");
lobbyData1.setSen(5);
lobbyData1.setUi(5);
lobbyData1.setFn("lulz");
lobbyData1.setPic("lulzagain");
lobbyData1.setInb(true);
lobbyData1.setT(5);
lobbyData1.setS(5);
return lobbyData1;
}
As you already figured out, you should use registerClassAlias as the RemoteClass works out of the box only for Flex projects (as bindable, etc).
Be sure to call registerClassAlias before any serializing / deserializing occurs.
Also, the debugger is showing you the actual tipe of your "o" parameter, which is object. This shows that the player is not correctly mapping the AMF serialized object's class to any of your classes (so, by default, it goes with Object). You should see a LobbyData object in the debugger; otherwise, no matter how you cast / coerce it, it won't work.
The objet needs to be declared before the responder is called.
public function refreshRoom(event:Event)
{
var testObject:LobbyData=new LobbyData;
var resp:Responder=new Responder(handleResp,null);
ncLobby.call("getLobbyData", resp, null);
}
public function handleResp(o:Object):void
{
testObject = o as LobbyData;
trace(testObject);
}
Actually if you want to workaround the type casting you can simply add this to your constructor:
public function dataAwareObject(o:* = null)
{
//TODO: implement function
super();
if(o){
for(var a:* in o)
this[a] = o[a];
}
}
}
Works like a charm.