parse json for GWT SuggestBox - json

I want to parse a json response in Java and add its values to a suggestBox in GWT. It would be great if anyone can help me with a sample code.
["abc","def","ghi","jkl","mno","pqr","acb","dfe","gih","jlk","mon"]
public void parseResponse(String str){
MultiWordSuggestOracle oracle = new MultiWordSuggestOracle();
JSONValue jsonValue = JSONParser.parseLenient(str);
JSONArray jArray = jsonValue.isArray();
for(int i=0; i<jArray.size(); i++){
String companySymbol = jArray.get(i).isString().toString();
oracle.add(companySymbol);
}
}

You cannot use MultiWordSuggestOracle: you have to extend http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/SuggestOracle.html
(and its callback)
ex:
class MySuggestOrc extends SuggestOracle {
public void requestSuggestions(final SuggestOracle.Request request, final SuggestOracle.Callback callback) {
Receiver<YourJsonContainer> receiver = new Receiver<YourJsonContainer>() {
#Override
public void onSuccess(YourJsonContainer companiesJsonHolder) {
List<Suggestion> companies = //... the code to split json
SuggestOracle.Response response = new SuggestOracle.Response();
response.setSuggestions(companies)
callback.onSuggestionsReady( request, response );
}
}
AsyncRequest req = // get you json respons here and use ...
}
}

Related

How to add attachment using TestRail API?

public static void fnUpdateResultToTestRail(String trusername, String trpassword, String trRunId,String testCaseName,String status, String testStepDetails)
throws MalformedURLException, IOException, APIException {
APIClient client = new APIClient("testrailurl");
client.setUser("username");
client.setPassword("password");
HashMap data = new HashMap();
data.put("status_id", status);
data.put("comment", testStepDetails);
HashMap data1 = new HashMap();
data1.put("attachment","C:\\Pictures\\\\X-SecurityToken-Issue.jpg";
JSONArray array = (JSONArray) client.sendGet("get_tests/"+trRunId);
//System.out.println(array.size());
for (int i = 0; i < array.size(); i++) {
JSONObject c = (JSONObject) (array.get(i));
String testrailTestCaseName=c.get("title").toString();
if (testrailTestCaseName.equals(testCaseName)) {
System.out.println(c.get("id"));
client.sendPost("add_result/" + c.get("id"), data);
client.sendPost("add_attachment_to_case/"+c.get("case_id"), data1);
break;
}
}
}
TestRail API returned HTTP 400("No file attached or upload size was exceeded.")
As per document, we need to pass Headers: { "Content-Type","value":"multipart/form-data" }
API client has inbuilt methods....
public Object sendPost(String uri, Object data)
throws MalformedURLException, IOException, APIException
{
return this.sendRequest("POST", uri, data);
}
private Object sendRequest(String method, String uri, Object data)
throws MalformedURLException, IOException, APIException
{
URL url = new URL(this.m_url + uri);
...........
}
How to add the header in this inbuilt method on run time..?
Can any one help on this?

How to correctly handle data management with SharedPreferences?

Right now, I am in the process of "optimizing" my app. I am still a beginner, so what I am doing is basically moving methods from my MainActivity.class to their separate class. I believe it's called Encapsulation (Please correct me if I'm wrong).
My application needs to :
Get a YouTube Playlist Link from the YouTube App (with an Intent, android.intent.action.SEND).
Use the link to fetch data from the Google Servers with the YouTubeApi and Volley.
Read the data received and add it to an arrayList<String>.
What my YouTubeUsage.java class is supposed to do, is fetch data with the YouTubeApi and Volley then store the data using SharedPreferences. Once the data is saved, the data is being read in my ConvertActivity.class (It's an activity specifically created for android.intent.action.SEND) with my method getVideoIds() before setting an adapter for my listView in my createRecyclerView() method.
YouTubeUsage.java
public class YoutubeUsage {
private Boolean results = false;
private String mResponse;
private ArrayList<String> videoIds = new ArrayList<>();
String Url;
public String getUrl(String signal) {
String playlistId = signal.substring(signal.indexOf("=") + 1);
this.Url = "https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails%2C%20snippet%2C%20id&playlistId=" +
playlistId + "&maxResults=25&key=" + "API_KEY";
return this.Url;
}
public void fetch(String Url, final Context context){
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.GET, Url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
sharedPreferences(response, context);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VolleyError", Objects.requireNonNull(error.getMessage()));
}
});
queue.add(request);
}
private void sharedPreferences(String response, Context context){
SharedPreferences m = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = m.edit();
if (m.contains("serverResponse")){
if (!m.getString("serverResponse", "").equals(response)){
editor.remove("serverResponse");
editor.apply();
updateSharedPreferences(response, context);
}
} else{
updateSharedPreferences(response, context);
}
}
private void updateSharedPreferences(String mResponse, Context mContext){
SharedPreferences m = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = m.edit();
editor.putString("serverResponse", mResponse);
editor.apply();
}
}
ConvertActivity.java
public class ConvertActivity extends AppCompatActivity {
YoutubeUsage youtubeUsage = new YoutubeUsage();
ArrayList<String> videoIDs = new ArrayList<>();
String Url = "";
ListView listView;
MyCustomAdapter myCustomAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
listView = findViewById(R.id.listview_convert);
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if ("android.intent.action.SEND".equals(action) && "text/plain".equals(type)) {
Url = youtubeUsage.getUrl(Objects.requireNonNull(intent.getStringExtra("android.intent.extra.TEXT")));
}
//I would like to avoid the try/catch below
try {
videoIDs = getVideoIDs(Url, this);
createRecyclerView(videoIDs);
Log.i("ResponseVideoIDs", String.valueOf(videoIDs.size()));
} catch (JSONException e) {
e.printStackTrace();
}
}
private ArrayList<String> getVideoIDs(String Url, Context context) throws JSONException {
ArrayList<String> rawVideoIDs = new ArrayList<>();
youtubeUsage.fetch(Url, context);
SharedPreferences m = PreferenceManager.getDefaultSharedPreferences(context);
String serverResponse = m.getString("serverResponse", "");
JSONObject jsonObject = new JSONObject(serverResponse);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i<jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId = jsonObject1.getJSONObject("contentDetails");
rawVideoIDs.add(jsonVideoId.getString("videoId"));
}
return rawVideoIDs;
}
private void createRecyclerView(ArrayList<String> videoIDs){
myCustomAdapter = new MyCustomAdapter(this, videoIDs);
listView.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
}
}
Everything works fine, however, my sharedPreferences never gets updated. Which means, if I share a YouTube playlist from the YouTube App to my app with 3 items in it, it will work fine. The Listview will show 3 items with their corresponding IDs as it should. But, if I share a YouTube playlist again, my app will still hold on to the data of the previous playlist I shared (even if I close it), showing the item number and the IDs of the previous link. If i continue to share the same playlist over and over, it will eventually show the correct number of items and the correct IDs.
I could totally put all my methods from the YouTubeUsage.java in my ConvertActivity.class preventing me from using SharedPreferences to transfer data between the two java classes. However, JSON throws an exception. That means I have to encapsulate my code with try/catch. I would like to avoid those since I need to do a lot of operations on the data just received by Volley (check a class size, look for certains strings). I find that doing this in these try/catch don't work like I want. (i.e. outside the try/catch, the values remains the same even if I updated them in the try/catch).
I want to know two things.
How can I correct this problem?
Is this the most efficient way to do this (optimization)? (I though of maybe
converting the VolleyResponse to a string with Gson then store the String file, but I don't know if that's the best way to do it since it's supposed to be
provisional data. It feels like just more of the same).
Thank You!
There is an issue with making assumptions about order of events. Volley will handle requests asynchronously, so it is advisable to implement the observer pattern here.
Create a new Java file that just contains:
interface MyNetworkResponse {
void goodResponse(String responseString);
}
Then make sure ConvertActivity implements MyNetworkResponse and create method:
void goodResponse(String responseString) {
// handle a positive response here, i.e. extract the JSON and send to your RecyclerView.
}
within your Activity.
In your YoutubeUsage constructor, pass in the Activity context (YoutubeUsage) and then store this in a YoutubeUsage instance variable called ctx.
In onCreate, create an instance of YoutubeUsage and pass in this.
In onResponse just call ctx.goodResponse(response).
Amend the following block to:
if ("android.intent.action.SEND".equals(action) && "text/plain".equals(type)) {
Url = youtubeUsage.getUrl(Objects.requireNonNull(intent.getStringExtra("android.intent.extra.TEXT")));
youtubeUsage.fetch(Url);
}
Delete the try/catch from onCreate.
And no need to use SharedPreferences at all.
UPDATE
Try this code:
MyNetworkResponse.java
interface MyNetworkResponse {
void goodResponse(String responseString);
void badResponse(VolleyError error);
}
YoutubeUsage.java
class YoutubeUsage {
private RequestQueue queue;
private MyNetworkResponse callback;
YoutubeUsage(Object caller) {
this.callback = (MyNetworkResponse) caller;
queue = Volley.newRequestQueue((Context) caller);
}
static String getUrl(String signal) {
String playlistId = signal.substring(signal.indexOf("=") + 1);
return "https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails%2C%20snippet%2C%20id&playlistId=" + playlistId + "&maxResults=25&key=" + "API_KEY";
}
void fetch(String url){
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.goodResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.badResponse(error);
}
});
queue.add(request);
}
}
ConvertActivity.java
public class ConvertActivity extends AppCompatActivity implements MyNetworkResponse {
YoutubeUsage youtubeUsage;
ArrayList<String> videoIDs = new ArrayList<>();
ListView listView;
MyCustomAdapter myCustomAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
listView = findViewById(R.id.listview_convert);
youtubeUsage = new YoutubeUsage(this);
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if ("android.intent.action.SEND".equals(action) && "text/plain".equals(type)) {
String url = YoutubeUsage.getUrl(Objects.requireNonNull(intent.getStringExtra("android.intent.extra.TEXT")));
youtubeUsage.fetch(url);
}
}
private ArrayList<String> getVideoIDs(String serverResponse) throws JSONException {
ArrayList<String> rawVideoIDs = new ArrayList<>();
JSONObject jsonObject = new JSONObject(serverResponse);
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId = jsonObject1.getJSONObject("contentDetails");
rawVideoIDs.add(jsonVideoId.getString("videoId"));
}
return rawVideoIDs;
}
private void createRecyclerView(ArrayList<String> videoIDs) {
myCustomAdapter = new MyCustomAdapter(this, videoIDs);
listView.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
}
#Override
public void goodResponse(String responseString) {
Log.d("Convert:goodResp", "[" + responseString + "]");
try {
ArrayList<String> rawVideoIDs = getVideoIDs(responseString);
createRecyclerView(rawVideoIDs);
} catch (JSONException e) {
// handle JSONException, e.g. malformed response from server.
}
}
#Override
public void badResponse(VolleyError error) {
// handle unwanted server response.
}
}

Using JSON in Android Studio in php style

I read JSON from webpage and now I want convert it to array and use like in php. In php I do it like that:
//$json - this is my json STRING readed from webpage
$trueJSON = json_decode($json,true);
$q = $trueJSON['test']['questions'][1]['question'];
$a1 = $trueJSON['test']['questions'][1]['answers']['a1'];
$a2 = $trueJSON['test']['questions'][1]['answers']['a2'];
$a3 = $trueJSON['test']['questions'][1]['answers']['a3'];
$a4 = $trueJSON['test']['questions'][1]['answers']['a4'];
$a5 = $trueJSON['test']['questions'][1]['answers']['a5'];
$a = $trueJSON['test']['questions'][1]['correctAnswer'];
In Android Studio to get json string from web I use this class:
public class TalkToServer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
String response = HttpRequest.get(params[0]).body();
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// and here I want to decode JSON string result to Array
// and next use this array on whole Activity
}
}
public void click(View view) {
TalkToServer task = new TalkToServer();
task.execute("http://quiz.xnicram.pl/getTest.php");
}
If possible then how to create in onPostExecute array which i can use in similar way to my php example?
PS. Sorry for my English :/
you can use this simple code
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray(/*Array Name */ );

.NET Core Configuration Serialization

Is there a way to serialize an object so that it could then be rehydrated by .Net Core Configuration Binder?
Basically, I'd like to get this Test to pass:
[Test]
public void Can_Serialize_And_Rehydrate()
{
var foo = new Foo{ Prop1 = 42; Prop2 = "Test" }
Dictionary<string, string> serialized = Serialize(Foo);
var deserializedFoo = new Foo();
new ConfigurationBuilder()
.AddInMemoryCollection(serialized)
.Build()
.Bind(deserializedFoo);
Assert.AreEqual(deserializedFoo.Prop1, 42);
Assert.AreEqual(deserializedFoo.Prop2, "Test");
}
Is there a Serializer out-of-the-box, or am I'm going to need to write my own Serialize() method?
AddInMemoryCollection's signature is like below, so why are you trying to serialize your dictionary here? You could just use it as it is.
public static IConfigurationBuilder AddInMemoryCollection(
this IConfigurationBuilder configurationBuilder,
IEnumerable<KeyValuePair<string, string>> initialData)
If you like to know more about how to test your custom configurations, I would suggest to look here:
https://github.com/aspnet/Configuration/blob/1.0.0/test/Microsoft.Extensions.Configuration.Binder.Test/ConfigurationBinderTests.cs
I was able to get this working by "hijacking" a JsonConfigurationProvider and plugging serialized Json directly into it. Not sure if this is the best way, but it does work:
public class ConfigurationSerializer
{
private class CustomJsonProvider : JsonConfigurationProvider
{
public CustomJsonProvider() : base(new JsonConfigurationSource())
{
}
public IDictionary<string, string> GetData(Stream s)
{
Load(s);
// Return the Configuration Dictionary
return Data;
}
}
public Dictionary<string, string> Serialize(object o)
{
var serialized =
JsonConvert.SerializeObject(
o,
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(serialized)))
{
var jsonProvider = new CustomJsonProvider();
return jsonProvider
.GetData(ms)
.ToDictionary(key => key.Key, value => value.Value);
}
}
}

How can I read this json on windows phone 8?

I'm trying to read the following json in a windows phone app using newtonsoft.json
I can't read anything. the also looks pretty strange to me.
{"type": "Menu","menu":
[{"0":"antipasto","tipo_piatto":"antipasto","1":"porchetta","nome_piatto":"porchetta","2":"1","prezzo":"1"},
{"0":"primo","tipo_piatto":"primo","1":"matriciana","nome_piatto":"matriciana","2":"5","prezzo":"5"},
{"0":"secondo","tipo_piatto":"secondo","1":"salsicce","nome_piatto":"salsicce","2":"4","prezzo":"4"},
{"0":"contorno","tipo_piatto":"contorno","1":"patate","nome_piatto":"patate","2":"2","prezzo":"2"},
{"0":"dolce","tipo_piatto":"dolce","1":"gelato","nome_piatto":"gelato","2":"6","prezzo":"6"}]}
this is my c# code for now
public class piatto_menu_giorno
{
public string tipo_piatto { get; set; }
public string nome_piatto { get; set; }
public string prezzo { get; set; }
}
public menu()
{
InitializeComponent();
WebClient webClient = new WebClient();
Uri uri = new Uri("http://www.stepapp.it/areacli/extDevice/getMenuOdierno_101.php");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(fine_lettura_web);
webClient.OpenReadAsync(uri);
}
private void fine_lettura_web(object sender, OpenReadCompletedEventArgs e)
{
DataContractJsonSerializer json = null;
json = new DataContractJsonSerializer(typeof(ObservableCollection<piatto_menu_giorno>));
ObservableCollection<piatto_menu_giorno> menu = json.ReadObject(e.Result) as ObservableCollection<piatto_menu_giorno>;
if(menu==null)
menu_giorno.Text = "null";
else
foreach (piatto_menu_giorno piatto in menu)
{
menu_giorno.Text += piatto.nome_piatto + "\n";
}
}
sorry for all the variables name that are in italian
I am writing a code for you it will help you to deserialize the object from json to yourClassCustomObject.
private async Task<List<piatto_menu_giorno>> MyDeserializerFunAsync()
{
List<piatto_menu_giorno> book = new List<piatto_menu_giorno>();
try
{
//I am taking my url from appsettings. myKey is my appsetting key. You can write direct your url.
string url = (string)appSettings["mykey"];
var request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json;odata=verbose";
var factory = new TaskFactory();
var task = factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse, null);
var response = await task;
Stream responseStream = response.GetResponseStream();
string data;
using (var reader = new System.IO.StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<piatto_menu_giorno>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
book = (List<piatto_menu_giorno>)json.ReadObject(ms);
return book;
}
}
Above code is working in my wp8 application it is faster you can try, it will help you. I am performing asynchronous operation but you can create your simple method with piatto_menu_giorno return type.