to display the data obtained from button listener to list- codename one - codenameone

I have a button that display the data obtained from json. below is my code for button action. I need help to display the data obtained to list.
#Override
protected void onMain_ButtonAction(final Component c, ActionEvent event) {
ConnectionRequest r = new ConnectionRequest() {
Hashtable h;
#Override
protected void postResponse() {
}
#Override
protected void readResponse(InputStream input) throws IOException {
InputStreamReader reader = new InputStreamReader(input);
JSONParser p = new JSONParser();
h = p.parse(new InputStreamReader(input));
Hashtable response = p.parse(reader);
Hashtable feed = (Hashtable)response.get("root");
for (Object s : h.values()) {
Vector vec = new Vector(100);
vec = (Vector)s;
int i;
for(i = 0; i<vec.size(); i++){
Hashtable<String, String> ht= (Hashtable<String, String>) vec.get(i);
System.out.println(ht.get("location"));
// findLabel().setText(ht.get("location"));
}
}
}
};
r.setUrl("http://ruslanapp.demo.capitaleyenepal.com/vodka-mobile-interface/getData/locations");
r.setPost(false);
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
r.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueue(r);
}
I want to list the data obtained frm btn above to the list below. how can I do it??
#Override
protected boolean initListModelList1(List cmp) {
cmp.setModel(new com.codename1.ui.list.DefaultListModel(new String[] {"Item 1", "Item 2", "Item 3"}));
return true;
}

You did most of the work well, I suggest avoiding a list and using an infinite container. The PropertyCross demo has pretty much this functionality (including JSON): https://www.udemy.com/learn-mobile-programming-by-example-with-codename-one/
To finish the code above create the model ArrayList above e.g. assuming you are using a MultiList:
// define this in the class variables:
private ArrayList<Map<String, String>> modelData = new ArrayList<Map<String, String>>();
// then in the code (I assumed stuff about your JSON, correct the
// code to extract the data correctly, just set the hashmap values
for (Object s : h.values()) {
Collection<Map<String, String>>) data = (Collection<Map<String, String>>))s;
for(Map<String, String> ht : data) {
String location = ht.get("location");
HashMap<String, String> entry = new HashMap<String, String>();
entry.put("Line1", location);
modelData.add(entry);
}
}
Then in:
#Override
protected boolean initListModelList1(List cmp) {
cmp.setModel(new DefaultListModel(modelData));
return true;
}
Notice that you should use showForm() to show the next form in the postResponse method.

Related

Getting a null Array from a method

I've created a method that shall return a two-dimensional Array, everything works perfectly as the array is being correctly filled in the method's try.
But once I display the array on onCreate(), it's returning null.
public class ListTickets extends AppCompatActivity {
public String[][] ticketTab ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tickets);
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
DisplayArray(getTicketsHTTP());
}
private String[][] getTicketsHTTP() {
final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray Jdata = response.getJSONArray("data");
for (int i=0; i < Jdata.length(); i++) {
try {
JSONObject oneTicket = Jdata.getJSONObject(i);
titreTicket = oneTicket.getString("1");
slaTicket = oneTicket.getString("30");
dateDebutTicket = oneTicket.getString("15");
urgenceTicket = oneTicket.getString("10");
statutTicket = oneTicket.getString("12");
idTicket = oneTicket.getString("2");
} catch (JSONException e) {
Log.e("Err", e.getMessage());
}
ticketTab[i][0] = titreTicket;
ticketTab[i][1] = slaTicket;
ticketTab[i][2] = dateDebutTicket;
ticketTab[i][3] = urgenceText(urgenceTicket);
ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket, dateEchanceTicket);
ticketTab[i][5] = String.valueOf(ticketEnretard);
ticketTab[i][6] = statutTicket;
ticketTab[i][7] = idTicket;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error.Response", error.toString());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("App-Token",FirstEverActivity.App_Token);
params.put("Session-Token",session_token);
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
return ticketTab;
}
}
I declared ticketTab outside the onCreate because when I declare it inside the method, I cannot change it inside the try.
How can I return the array correctly?
In your onCreate you are using this line:
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
and those values, nbTicket and nbTicketTab are not declared anywhere in your code, maybe that's why they are returning null, you have to initialize them and asign values.

if statement won't check through my array list

I was trying not to resort to posting on the forums but everything I've done will not make this work. What I'm trying to do is if an ArrayList doesn't contain a players name then it will add them to the ArrayList, but it's skipping over that and just removing them from the list they were never added to. Ultimate goal out of this plugin is if they are in god mode they can't be hurt.
Command Class:
public static List<String> playerList = new ArrayList<String>();
#Override
public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
Player player = (Player) sender;
String p = player.getName();
List<String> isGod = new ArrayList<String>();
if (cmd.getName().equalsIgnoreCase("god") && sender instanceof Player) {
if (!isGod.contains(p)) {
isGod.add(p);
playerList.add(p);
player.sendMessage(ChatColor.GREEN + "Godmode is enabled");
return true;
} else {
isGod.remove(p);
playerList.remove(p);
player.sendMessage(ChatColor.GREEN + "Godmode is disabled");
return true;
}
}
return true;
}
}
Listener Class:
#EventHandler
public void isDamaged(EntityDamageEvent e) {
String player = e.getEntity().getName();
if (playerList.contains(player)) {
e.setCancelled(true);
}
}
}
As dly said yes, you create new empty list every time command is executed. You must init your list as global static in your class in order to make sure that this is only one list for all operations.
public static List<String> isGod = new ArrayList<>(); // <== HERE
public static List<String> playerList = new ArrayList<String>();
#Override
public boolean onCommand(CommandSender sender, Command cmd, String str, String[] args) {
Player player = (Player) sender;
String p = player.getName();
if (cmd.getName().equalsIgnoreCase("god") && sender instanceof Player) {
if (!isGod.contains(p)) {
isGod.add(p);
playerList.add(p);
player.sendMessage(ChatColor.GREEN + "Godmode is enabled");
return true;
} else {
isGod.remove(p);
playerList.remove(p);
player.sendMessage(ChatColor.GREEN + "Godmode is disabled");
return true;
}
}
return true;
}

Store JSON Array from NewsAPI in Firebase

I have used volley to parse news data from the newsAPI.org. I want to save the response to Firebase for offline viewing and persistence.
This is the sample response from API:
articles: [
{
author: "Megan Rose Dickey",
title: "Ojo wants to be the electric scooter for commuters, but...",
description: "Commuting in a busy city like San Francisco can be
annoying..",
url: "https://techcrunch.com/2017/08/23/ojo-wants-to-be-the-electric-
scooter-for-commuters-but-its-not-there-yet/",
urlToImage: "https://img.vidible.tv/prod/2017",
publishedAt: "2017-08-23T21:19:56Z"
},
{
author: "Katie Roof",
title: "Pishevar intervenes in Benchmark-Kalanick lawsuit",
description: "Early Uber investor and former board member Shervin
Pishevar is speaking out against Benchmark again..",
url: "https://techcrunch.com/2017/08/24/pishevar-sends-another-letter-
to-uber-board-about-benchmark/",
urlToImage:"https://tctechcrunch2011.files.wordpress.com/",
publishedAt: "2017-08-24T22:49:59Z"
},
In total I have 5 objects inside the articles array.
I want to store each of the objects in Firebase database. This is what I have tried:
StringRequest stringRequest = new StringRequest(Request.Method.GET, Constants.NEWS_ENDPOINT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null){
Log.d(TAG, "News Api Response is: \t" + response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray articles = jsonObject.getJSONArray("articles");
for (int i = 0; i < articles.length(); i++){
JSONObject items = articles.getJSONObject(i);
final String title_news = items.getString("title");
final String desc_news = items.getString("description");
final String urlImg = items.getString("urlToImage");
final String author_news = items.getString("author");
final String url = items.getString("url");
final String publishedAt = items.getString("publishedAt");
NewsItem newsItem = new NewsItem(author_news, title_news, desc_news, url, urlImg, publishedAt);
itemList.add(newsItem);
/**
* Save JSON Results to Firebase
* */
for (int k = 0; k < articles.length(); k++){
HashMap hashMap = new HashMap();
hashMap.put("newsTitle", title_news);
hashMap.put("newsDesc", desc_news);
hashMap.put("newsImageUrl", urlImg);
hashMap.put("newsAuthor", author_news);
hashMap.put("newsUrl", url);
hashMap.put("newsDate", publishedAt);
newsRootRef.setValue(hashMap);
}
When I check the console, it saves only one object, the last object like this:
I want to store all objects AS-IS in the response array and retrieve them later. Is there another way to do this? Thanks, sorry for the long post.
In this case you need to use push() to store the data. Otherwise you are just replacing the data at the reference at each iteration. This is why it seems that only the last record gets stored. Try to change this line:
newsRootRef.setValue(hashMap);
...into this:
newsRootRef.push().setValue(hashMap);
To avoid duplicating entries I recommend that you fetch all entries from Firebase and cache the url property (since this property seems to be unique) in a HashSet. Then you can modify your code like this:
if (!urlSet.contains(url)) {
HashMap hashMap = new HashMap();
hashMap.put("newsTitle", title_news);
hashMap.put("newsDesc", desc_news);
hashMap.put("newsImageUrl", urlImg);
hashMap.put("newsAuthor", author_news);
hashMap.put("newsUrl", url);
hashMap.put("newsDate", publishedAt);
newsRootRef.push(),setValue(hashMap);
}
But of course you need to populate your HashSet first so I'd recommend doing something like this:
final Set<String> urlSet = new HashSet<>();
newsRootRef.addChildEventListener(new ChildEventListener() {
int i = 0;
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
urlSet.add(dataSnapshot.getValue(String.class));
if (i++ == dataSnapshot.getChildrenCount()) {
...
...your code...
StringRequest stringRequest = new StringRequest(Request.Method.GET, Constants.NEWS_ENDPOINT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
...
...
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

iOS save to storage issue

I've an issue while trying to save an image to the Storage in iOS. Image is downloaded but not saved.
The code is:
Form hi = new Form("Toolbar", new BoxLayout(BoxLayout.Y_AXIS));
TreeModel tm = new TreeModel() {
#Override
public Vector getChildren(Object parent) {
String[] files;
if (parent == null) {
files = FileSystemStorage.getInstance().getRoots();
return new Vector<Object>(Arrays.asList(files));
} else {
try {
files = FileSystemStorage.getInstance().listFiles((String) parent);
} catch (IOException err) {
Log.e(err);
files = new String[0];
}
}
String p = (String) parent;
Vector result = new Vector();
for (String s : files) {
result.add(p + s);
}
return result;
}
#Override
public boolean isLeaf(Object node) {
return !FileSystemStorage.getInstance().isDirectory((String) node);
}
};
Command tree = new Command("Show tree") {
#Override
public void actionPerformed(ActionEvent evt) {
Form treeForm = new Form("Tree", new BorderLayout());
Tree t = new Tree(tm) {
#Override
protected String childToDisplayLabel(Object child) {
String n = (String) child;
int pos = n.lastIndexOf("/");
if (pos < 0) {
return n;
}
return n.substring(pos);
}
};
treeForm.add(BorderLayout.CENTER, t);
Command back = new Command("Back") {
#Override
public void actionPerformed(ActionEvent evt) {
hi.showBack();
}
};
Button backButton = new Button(back);
treeForm.add(BorderLayout.SOUTH, backButton);
treeForm.show();
}
};
hi.getToolbar().addCommandToOverflowMenu(tree);
EncodedImage placeholder = EncodedImage.createFromImage(Image.createImage(hi.getWidth(), hi.getWidth() / 5, 0xffff0000), true);
String photoURL = "https://awoiaf.westeros.org/images/thumb/9/93/AGameOfThrones.jpg/400px-AGameOfThrones.jpg";
StringBuilder fsPath = new StringBuilder(FileSystemStorage.getInstance().getAppHomePath());
fsPath.append("400px-AGameOfThrones.jpg");
URLImage background = URLImage.createToStorage(placeholder, fsPath.toString(), photoURL);
background.fetch();
Style stitle = hi.getToolbar().getTitleComponent().getUnselectedStyle();
stitle.setBgImage(background);
stitle.setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FILL);
stitle.setPaddingUnit(Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS, Style.UNIT_TYPE_DIPS);
stitle.setPaddingTop(15);
SpanButton credit = new SpanButton("Link");
credit.addActionListener((e) -> Display.getInstance().execute("https://awoiaf.westeros.org/index.php/A_Game_of_Thrones"));
hi.add(new SpanLabel("A")).
add(new Label("B", "Heading")).
add(credit);
ComponentAnimation title = hi.getToolbar().getTitleComponent().createStyleAnimation("Title", 200);
hi.getAnimationManager().onTitleScrollAnimation(title);
hi.show();
Which was taken from https://www.codenameone.com/javadoc/com/codename1/ui/URLImage.html
The tree is only to see if the image was saved in the Storage.
You are mixing Storage & FileSystemStorage which are very different things see this.
You can use storage which is a flat set of "files" and that's what URLImage.createToStorage does. But then you need to use the Storage API to work with that and it might not be visible in the FileSystemStorage API.
Alternatively you might be looking for URLImage.createToFileSystem().

FileInputFormat where filename is KEY and text contents are VALUE

I'd like to use an entire file as a single record for MAP processing, with the filename as the key.
I've read the following post: How to get Filename/File Contents as key/value input for MAP when running a Hadoop MapReduce Job?
and while the theory of the top answer is solid, no code or "how-to" is actually provided.
Here is my custom FileInputFormat and the corresponding RecordReader, which compile, yet do not produce ANY record data.
Thanks for any help.
public class CommentsInput
extends FileInputFormat<Text,Text> {
protected boolean isSplitable(FileSystem fs, Path filename)
{
return false;
}
#Override
public RecordReader<Text, Text> createRecordReader(InputSplit split, TaskAttemptContext ctx)
throws IOException, InterruptedException {
return new CommentFileRecordReader((FileSplit) split, ctx.getConfiguration());
}
/////////////////////////
public class CommentFileRecordReader
extends RecordReader<Text,Text> {
private InputStream in;
private long start;
private long length;
private long position;
private Text key;
private Text value;
private boolean processed;
private FileSplit fileSplit;
private Configuration conf;
public CommentFileRecordReader(FileSplit fileSplit, Configuration conf) throws IOException
{
this.fileSplit = fileSplit;
this.conf=conf;
}
/** Boilerplate initialization code for file input streams. */
#Override
public void initialize(InputSplit split,
TaskAttemptContext context)
throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
fileSplit = (FileSplit) split;
this.start = fileSplit.getStart();
this.length = fileSplit.getLength();
this.position = 0;
this.processed = false;
Path path = fileSplit.getPath();
FileSystem fs = path.getFileSystem(conf);
FSDataInputStream in = fs.open(path);
CompressionCodecFactory codecs = new CompressionCodecFactory(conf);
CompressionCodec codec = codecs.getCodec(path);
if (codec != null)
this.in = codec.createInputStream(in);
else
this.in = in;
// If using Writables:
// key = new Text();
// value = new Text();
}
public boolean next(Text key, Text value) throws IOException
{
if(!processed)
{
key = new Text(fileSplit.getPath().toString());
Path file = fileSplit.getPath();
FileSystem fs = file.getFileSystem(conf);
FSDataInputStream in = null;
byte[] contents = new byte[(int) fileSplit.getLength()];
try
{
in = fs.open(file);
IOUtils.readFully(in, contents, 0, contents.length);
value.set(contents.toString());
}
finally
{
IOUtils.closeStream(in);
}
processed = true;
return true;
}
return false;
}
#Override
public boolean nextKeyValue() throws IOException {
// TODO parse the next key value, update position and return true.
return false;
}
#Override
public Text getCurrentKey() {
return key;
}
#Override
public Text getCurrentValue() {
return value;
}
/** Returns our progress within the split, as a float between 0 and 1. */
#Override
public float getProgress() {
if (length == 0)
return 0.0f;
return Math.min(1.0f, position / (float)length);
}
#Override
public void close() throws IOException {
if (in != null)
in.close();
}
}
You need to find a way to define your own key class and make sure your classes use it. You can look up how to define your own key class and you can get a file name by calling hte getName() method on its path then use it to make your key.

Resources