Get Items Feeds4J Java Array - java

Im from php, so i want to lear java.
In php in a for loop if i want to create an array i just do
$items = $this->getItems();
for($i=0;$i<count($items);$i++)
{
$myarrayitems[$i] = $items[$i];
}
return $myarrayitems;
But in java i got arrayoutofexponsion or like that.
here is the code im trying
public String[] getItems(String url) throws Exception
{
URL rss = new URL(url);
Feed feed = FeedParser.parse(rss);
int items = feed.getItemCount();
int a = 0;
for (int i = 0; i < items; i++)
{
FeedItem item = feed.getItem(i);
String title[i] = item.getTitle();
}
return title;
}
How can i return title as array an make an var_dump of that?

You need to create the array with the right number of elements to start with. Something like this:
public String[] getItems(String url) throws Exception
{
URL rss = new URL(url);
Feed feed = FeedParser.parse(rss);
int items = feed.getItemCount();
// We know how many elements we need, so create the array
String[] titles = new String[items];
for (int i = 0; i < items; i++)
{
titles[i] = feed.getItem(i).getTitle();
}
return titles;
}
A potentially nicer alternative, however, is to return a List<String> instead of a string array. I don't know the FeedParser API, but if you can iterate over the items instead you could do something like:
public List<String> getItems(String url) throws Exception
{
URL rss = new URL(url);
Feed feed = FeedParser.parse(rss);
List<String> titles = new ArrayList<String>();
for (Item item : feed)
{
titles.add(item.getTitle());
}
return titles;
}
This will work even if you don't know how many items there are to start with. When Java eventually gets concise closures, you may well be able to express this even more simply, as you would in C# with LINQ :)

You have to define title as an array before using using it:
String title = new String[ARRAY_DIMENSION];
If you don't know ARRAY_DIMENSION you could use this:
List<String> title = new ArrayList<String>();
or this, if you do not mind String order in the ArrayList:
Collection<String> title = new ArrayList<String>();

Related

Javafx: Reading from an File and Spliting the result with .split method

I want to by reading the data of a file to split the results based on .split(",") in another words for this particular example i want to have 2 Indexes with each containing up to 5 informations which i would also like to acces with the .[0] and .[1] Method.
the File with the Data.
File Reading Method.
public void fileReading(ActionEvent event) throws IOException {
File file = new File("src/DateSpeicher/datenSpeicher.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null) {
System.out.println(st);
}
}
The method does work very greatly however, i wonder how can i split those two in two Indexes or String arrays which both can be accessed through respective indecies [0], [1]. For first data in the firm array - 655464 [0][0] for last in the second Array [1][4].
My approach:
1. Making an ArrayList for every ,
2. Adding data till ","
Issue: eventho approach above works, you cant do such things as array1[0] - it gives an error, however the index method is crucial.
How can i solve this problem?
Path path = Paths.get("src/DateSpeicher/datenSpeicher.txt"); // Or:
Path path = Paths.get(new URL("/DateSpeicher/datenSpeicher.txt").toURI());
Either two Strings, and then handling them:
String content = new String(Files.readAllBytes(path), Charset.defaultCharset());
String[] data = content.split(",\\R");
or a list of lists:
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
// Result:
List<List<String>> lists = new ArrayList<>();
List<String> newList = null;
boolean addNewList = true;
for (int i = 0; i < lines.size(); ++i) {
if (addNewList) {
newList = new ArrayList<>();
lists.add(newList);
addNewList = false;
}
String line = lines.get(i);
if (line.endsWith(",")) {
line = line.substring(0, line.length() - 1);
addNewList = true;
}
newList.add(line);
}

Breaking down textfile into Arraylist - Java

I am trying to break down a data text file which is in the format of:
kick, me, 10
kick, you, 20
into arrayList<customlist> = new arrayList
class customlist
{
string something, string something2, int times
}
So my question is how can I get each part of the text file data to each part of the customlist.
eg: kick -> something, me -> something2 and 10 -> times
Try to split each line into its components using String.split(",").
Apply String.trim() to each member in order to get rid of the spaces.
There are many way to solve this type of problem, here you can simply read all text from that text file by using InputStream and BufferReader after geting all text you can do somthing like:-
ArrayList<CustomList> getArrayList(String textFileData)
{
ArrayList<CustomList> customLists = new ArrayList<>() ;
String data[] = textFileData.split(",");
int i = data.length;
int position = 0;
while (position<i)
{
String somthing = data[position];
String somthing1 = data[position+1];
String temp = data[position+2].split(" ")[0];
int times = Integer.parseInt(temp);
CustomList customList= new CustomList();
customList.setSomething(somthing);
customList.setSomething2(somthing1);
customList.setTimes(times);
customLists.add(customList);
position = position+3;
}
return customLists;
}
Note: this is refer if you are using same string pattern as you mention in the above problem
Using a Scanner object to read the lines and breaking up each line using the split() function. Then, create a new customlist object, and add it into your ArrayList<customlist>.
public void readFile(File file, ArrayList<customlist> myList)
{
Scanner sc = new Scanner(file);
String line;
while(sc.hasNextLine())
{
line=sc.nextLine();
String[] fields = line.split(",");
int times = Integer.parseInt(fields[2].trim());
customlist myCustom = new myList(fields[0].trim(), fields[1].trim(),
times);
myList.add(myCustom);
}
sc.close();
}
You may also handle exceptions if you think its necessary.

How to clear an ArrayList without affecting next funciton?

I am trying to read a file and pass it to a class called "Allabaque" that has a String and two List. When I have finished reading the first abaque I want to clear the two Lists so I can get the nexts values but if I clear the List, even if I do it after adding the new abaque, the function passes me the new abaque with the two empty Lists. Here is the code:
public void importFrom(String filename) {
try (
FileInputStream fis = new FileInputStream(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));) {
String line;
String line2;
int c = 0;
List<String> Pression = new ArrayList<>();
List<String> Couple = new ArrayList<>();
List<String> P2 = new ArrayList<>();
List<String> C2 = new ArrayList<>();
String Cle = "null";
while ((line = reader.readLine()) != null) {
if (c == 2 && !"|".equals(line)) {
String[] arg = line.split("-");
boolean u = Pression.add(arg[0]);
boolean u2 = Couple.add(arg[1]);
}
if (c == 1) {
Cle = line;
c = 2;
//System.out.printf("%s",Cle);
}
if ("|".equals(line)) {
c = 1;
if (!"null".equals(Cle)) {
//P2 = Pression;
//C2 = Couple;
addAbaque(new Abaque(Cle, Pression, Couple));//addAbaque(new Abaque(Cle,P2,C2));
Couple.clear();
Pression.clear();
}
}
}
} catch (IOException ioe) {
System.out.printf("Erreur import");
}
}
The addAbaque method is the simple
public void addAbaque(Abaque abaque) {
mAbaques.add(abaque);``
}
Using the debug I think I have found that it's a problem with the memory but I reaaly dont know how to fix it.
I've tried also with two intermedieries List, I putted it like comments, but still nothing.
Clearing the Couple and Pression lists also clears the lists previously passed to the Abaque constructor, since you are passing List references to the constructor, not copies of the lists.
You can either pass new Lists to the constructor :
addAbaque(new Abaque(Cle,new ArrayList<String>(Pression),new ArrayList<String>(Couple)));
Or create new Lists instead of clearing the old ones, i.e. replace
Couple.clear();
Pression.clear();
with
Couple = new ArrayList<>();
Pression = new ArrayList<>();
The latter alternative is probably more efficient, since you don't have to copy the contents of the original Lists to new Lists, and you don't have to clear any Lists.

How to parse JSON Array (Not Json Object) in Android

I have a trouble finding a way how to parse JSONArray.
It looks like this:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
I know how to parse it if the JSON was written differently (In other words, if I had json object returned instead of an array of objects).
But it's all I have and have to go with it.
*EDIT: It is a valid json. I made an iPhone app using this json, now I need to do it for Android and cannot figure it out.
There are a lot of examples out there, but they are all JSONObject related. I need something for JSONArray.
Can somebody please give me some hint, or a tutorial or an example?
Much appreciated !
use the following snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
I'll just give a little Jackson example:
First create a data holder which has the fields from JSON string
// imports
// ...
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyDataHolder {
#JsonProperty("name")
public String mName;
#JsonProperty("url")
public String mUrl;
}
And parse list of MyDataHolders
String jsonString = // your json
ObjectMapper mapper = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(jsonString,
new TypeReference<ArrayList<MyDataHolder>>() {});
Using list items
String firstName = list.get(0).mName;
String secondName = list.get(1).mName;
public static void main(String[] args) throws JSONException {
String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String name = obj.getString("name");
String url = obj.getString("url");
System.out.println(name);
System.out.println(url);
}
}
Output:
name1
url1
name2
url2
Create a class to hold the objects.
public class Person{
private String name;
private String url;
//Get & Set methods for each field
}
Then deserialize as follows:
Gson gson = new Gson();
Person[] person = gson.fromJson(input, Person[].class); //input is your String
Reference Article: http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/
In this example there are several objects inside one json array. That is,
This is the json array: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
This is one object: {"name":"name1","url":"url1"}
Assuming that you have got the result to a String variable called jSonResultString:
JSONArray arr = new JSONArray(jSonResultString);
//loop through each object
for (int i=0; i<arr.length(); i++){
JSONObject jsonProductObject = arr.getJSONObject(i);
String name = jsonProductObject.getString("name");
String url = jsonProductObject.getString("url");
}
public class CustomerInfo
{
#SerializedName("customerid")
public String customerid;
#SerializedName("picture")
public String picture;
#SerializedName("location")
public String location;
public CustomerInfo()
{}
}
And when you get the result; parse like this
List<CustomerInfo> customers = null;
customers = (List<CustomerInfo>)gson.fromJson(result, new TypeToken<List<CustomerInfo>>() {}.getType());
A few great suggestions are already mentioned.
Using GSON is really handy indeed, and to make life even easier you can try this website
It's called jsonschema2pojo and does exactly that:
You give it your json and it generates a java object that can paste in your project.
You can select GSON to annotate your variables, so extracting the object from your json gets even easier!
My case
Load From Server Example..
int jsonLength = Integer.parseInt(jsonObject.getString("number_of_messages"));
if (jsonLength != 1) {
for (int i = 0; i < jsonLength; i++) {
JSONArray jsonArray = new JSONArray(jsonObject.getString("messages"));
JSONObject resJson = (JSONObject) jsonArray.get(i);
//addItem(resJson.getString("message"), resJson.getString("name"), resJson.getString("created_at"));
}
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
Old post I know, but unless I've misunderstood the question, this should do the trick:
s = '[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"}]';
eval("array=" + s);
for (var i = 0; i < array.length; i++) {
for (var index in array[i]) {
alert(array[i][index]);
}
}
URL url = new URL("your URL");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
//setting the json string
String finalJson = buffer.toString();
//this is your string get the pattern from buffer.
JSONArray jsonarray = new JSONArray(finalJson);

Using JSON data in the URLs found in my array

I am trying to use the 2nd value of each of my JSON elemnts and use it in a array of web urls. What I am trying to end of with is a array of urls that include the image names from my json data below.
JSON Data:
[["1","Dragon Neck Tattoo","thm_polaroid.jpg","polaroid.jpg"],["2","Neck Tattoo","thm_default.jpg","default.jpg"],["3","Sweet Tattoo","thm_enhanced-buzz-9667-1270841394-4.jpg","enhanced-buzz-9667-1270841394-4.jpg"]]
MainActivity:
Bundle bundle = getIntent().getExtras();
String jsonData = bundle.getString("jsonData");
try {
//THIS IS WHERE THE VALUES WILL GET ASSIGNED
JSONArray jsonArray = new JSONArray(jsonData);
private String[] mStrings=
{
for(int i=0;i<jsonArray.length();i++)
{
"http://www.mywebsite.com/images/" + jsonArray(i)(2),
}
}
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mStrings);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As I mentioned in a previous answer, a JSONArray is just an object, not a numerically-indexable array. It looks like you're having trouble with basic Java syntax, as well.
If you actually want to use a String[], not a List<String>:
private String[] mStrings = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++)
{
String url = jsonArray.getJSONArray(i).getString(2);
mStrings[i] = "http://www.mywebsite.com/images/" + url;
}
If the LazyAdapter you're using can take a List, that'll be even easier to work with:
private List<String> mStrings = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++)
{
String url = jsonArray.getJSONArray(i).getString(2);
mStrings.add("http://www.mywebsite.com/images/" + url);
}

Categories