How to retrieve RSS FEED from Yahoo weather - android

I've tried to retrieve RSS data from Yahho weather ,however my code couldn't work.
May I know what's wrong with it?
The Url that I've use is http://weather.yahooapis.com/forecastrss?w=1062617&u=c.
I'm a newbie in programming, Kindly seek your advice to it.
Thanks
the below are my coding.
CXActivity.java
public class CXActivity extends Activity {
/** Called when the activity is first created. */
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RestClient rc = new RestClient();
//the account key might not work. Please insert your own set.
ArrayList<Weather> list1 = rc.getPlaces("", "");
int index = 3;
String[] listArray = new String[list1.size()];
StringBuilder sb = new StringBuilder();
int counter = 0;
for(int i = 1; i<list1.size(); i++)
{
sb.append("\n\nEntry #: " + i);
sb.append("\n" + "Title: \""+ list1.get(i).getTitle() + "\"");
sb.append("\n" + "Publish Date: \""+ list1.get(i).getPubDate() +"\"");
sb.append("\n" + "Condition: \""+ list1.get(i).getCondition()+"\"");
sb.append("\n" + "Forecast: \""+ list1.get(i).getForecast()+"\"");
listArray[counter] = sb.toString();
counter++;
sb.delete(0, sb.capacity());
}
listview=(ListView)findViewById(R.id.ListView01);
listview.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , listArray));
}
}
RestClient.java
public class RestClient
{
ArrayList weatherList;
//This is the function responsible to pull data from web service.
public ArrayList<Weather> getPlaces(String accountKey, String uniqueId)
{
weatherList = new ArrayList<Weather>();
try {
URL _url = new URL("http://weather.yahooapis.com/forecastrss?w=1062617&u=c");
URLConnection _urlConn = _url.openConnection();
_urlConn.addRequestProperty("AccountKey", accountKey);
_urlConn.addRequestProperty("UniqueUserID", uniqueId);
BufferedReader br = new BufferedReader(new InputStreamReader(_urlConn.getInputStream()));
String line = null;
StringBuilder strBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
strBuilder.append(line);
System.out.println(line);
}
String[] IProperties = strBuilder.toString().split("<m:properties>");
for (String str : IProperties)
{
Weather weather = new Weather();
weather.setTitle(Utils.getStringBetween(str, "<title>", "</<title>>"));
weather.setPubDate(Utils.getStringBetween(str, "<pubDate>", "</pubDate>"));
weather.setCondition(Utils.getStringBetween(str, "<yweather:condition>", "</yweather:condition>"));
weather.setForecast(Utils.getStringBetween(str, "<yweather:forecast>", "</yweather:forecast>"));
weatherList.add(weather);
}
}
catch (MalformedURLException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
return weatherList;
}
//This is a helper function to get specific traffic data structure
public Weather getPlacesAtIndex(ArrayList<Weather> list, int index)
{
if(list.size() <= index) return null;
return list.get(index);
}
}
Utils.java
public class Utils {
//This functions get the xml data between the xml elements
public static String getStringBetween(String src, String start, String end)
{
StringBuilder sb = new StringBuilder();
int startIdx = src.indexOf(start) + start.length();
int endIdx = src.indexOf(end);
while(startIdx < endIdx)
{
sb.append("" + String.valueOf(src.charAt(startIdx)));
startIdx++;
}
return sb.toString();
}
}
weather.java
public class Weather {
String Title;
String PubDate;
String Condition;
String Forecast;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getPubDate() {
return PubDate;
}
public void setPubDate(String pubDate) {
PubDate = pubDate;
}
public String getCondition() {
return Condition;
}
public void setCondition(String condition) {
Condition = condition;
}
public String getForecast() {
return Forecast;
}
public void setForecast(String forecast) {
Forecast = forecast;
}
}

Please change your activity code.
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RestClient rc = new RestClient();
// the account key might not work. Please insert your own set.
ArrayList<Weather> list1 = rc.getPlaces("", "");
int index = 3;
String[] listArray = new String[list1.size()];
StringBuilder sb = new StringBuilder();
int counter = 0;
Log.e("N", "listArray::" + list1.size());
for (int i = 0; i < list1.size(); i++) {
sb.append("\n\nEntry #: " + i);
sb.append("\n" + "Title: \"" + list1.get(i).getTitle() + "\"");
sb.append("\n" + "Publish Date: \"" + list1.get(i).getPubDate()
+ "\"");
sb.append("\n" + "Condition: \"" + list1.get(i).getCondition()
+ "\"");
sb.append("\n" + "Forecast: \"" + list1.get(i).getForecast() + "\"");
listArray[counter] = sb.toString();
counter++;
sb.delete(0, sb.capacity());
}
Log.e("N", "listArray::" + listArray.length);
listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listArray));
}
}

Related

How can I rearrange the data from database in a ListView?

everyone. I have an ArrayList of the data and a ListView to showing up the list of the data. Now what I want to do is rearrange the data when I press the button and sort the data in which data has the highest result.
Here is my code:
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
String[] dataDetail;
ArrayList<dataDetail> allDetail = new ArrayList<>();
ListView detailList;
final Context context = this;
final int min = 0;
final int max = 10;
final int random = new Random().nextInt((max - min) + 1) + min;
Button reorder = findViewById(R.id.arrangeId);
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detailList = findViewById(R.id.dataView);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
new GetData().execute();
}
private class GetData extends AsyncTask<Void, Void, ArrayList<dataDetail>> {
protected ArrayList<dataDetail> doInBackground(Void... voids) {
HttpURLConnection urlConnection;
InputStream in = null;
try {
URL url = new URL("http://10.0.2.2:8080/projectServer/DataDetailDB?getdata=true");
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String response = convertStreamToString(in);
System.out.println("Server response = " + response);
try {
JSONArray jsonArray = new JSONArray(response);
dataDetail = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
final String customerName = jsonArray.getJSONObject(i).get("customerName").toString();
final String carName = jsonArray.getJSONObject(i).get("carName").toString();
final String appointmentDate = jsonArray.getJSONObject(i).get("appointmentDate").toString();
final String email = jsonArray.getJSONObject(i).get("email").toString();
final String issueDescribe = jsonArray.getJSONObject(i).get("issueDescribe").toString();
final String timeForJob = jsonArray.getJSONObject(i).get("timeForJob").toString();
final String costForJob = jsonArray.getJSONObject(i).get("costForJob").toString();
final String reliableOnCar = jsonArray.getJSONObject(i).get("reliableOnCar").toString();
final String distanceJob = jsonArray.getJSONObject(i).get("distance").toString();
dataDetail tData = new dataDetail(customerName, carName, appointmentDate, email, issueDescribe, timeForJob, costForJob, reliableOnCar, distanceJob);
allDetail.add(tData);
System.out.println("customername = " + customerName + "carname = " + carName + "appointmentdate = " + appointmentDate +
"email = " + email + "describe = " + issueDescribe + "time = " + timeForJob + "cost = " + costForJob + "reliable = " + reliableOnCar
+ "dis = " + distanceJob);
dataDetail [i] = "Name: " + customerName + "\n" + "Appointment Date: " + appointmentDate;
reorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float finalResult = random * Float.parseFloat(timeForJob) + random * Float.parseFloat(reliableOnCar) +
random * Float.parseFloat(distanceJob) + random * Float.parseFloat(costForJob);
System.out.print("Test result " + finalResult + " ");
/* Trying to sort the data here which has the highest finalResult
* will going to the top of the list */
allDetail = new ArrayList<String>(Arrays.asList(dataDetail));
Collections.sort(allDetail);
ArrayAdapter newList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail);
newList.setAdapter(theList);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(ArrayList<dataDetail> dataDetailArrayList) {
super.onPostExecute(dataDetailArrayList);
ArrayAdapter theList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail);
detailList.setAdapter(theList);
}
}
public String convertStreamToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
But when I try to use sort I get the error says it's incompatible types.
allDetail = new ArrayList<String>(Arrays.asList(dataDetail));
Collections.sort(allDetail);
The finalResult will do the calculation and get the final result for every data it retrieves from the database. And now I just want to reorder it automatically, This is the logcat:
Please anyone can help how can I do the rearrange for the listview?
Collections.sort() will work. Its your problem related to how your are storing your data in list

my table is full in class and empty in other

I'am a beginner in android and i use AndroidStudio
I have a problem
in have 2 class i my project in the first class "fetch compte" i fill my table "dataParsed" and i 'am certain that the table is fil
but in the second class MainActivity
I find that the table is empty
please help me
this is my code
public class fetchcompte extends AsyncTask<Void,Void,Void> {
String data = "";
String dat = "";
public static String[] dataParsed ;
String singleParsed ;
String dataParse = "";
String singleParse1 = "";
String singleParse2 = "";
String singleParse3 = "";
String singleParse4 = "";
String singleParse5 = "";
private RequestQueue mQueue, mQueu;
int nbcompte;
protected Void doInBackground(Void... voids) {
String S = jsonArray;
// singleParsed=new String[20];
dataParsed=new String[20];
try {
// String url2="http://recrutement.stb.com.tn:1010/PlateformeApi_Externe/api/ComptesClient/000001498675\n";
//String url2 = "http://10.1.11.168:8081/my/banks/10/accounts/10403082500589678844/transactions";
String url2 = "http://10.12.0.66:8081/api/ComptesClient/000001498675";
URL url = new URL(url2);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
nbcompte=JA.length();
for(int i =0 ;i<nbcompte; i++) {
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "fullname:" + JO.get("fullname");
singleParse1 = "accountnumber:" + JO.get("accountnumber");
singleParse2 = "rib:" + JO.get("rib");
singleParse3 = "iban:" + JO.get("iban");
singleParse4 = "name:" + JO.get("name");
singleParse5 = "balance:" + JO.get("balance");
dataParsed[i] = singleParsed + "\n" + singleParse1 + "\n" + singleParse2 + "\n" + singleParse3 + "\n" + singleParse4 + "\n" + singleParse5;
}
// dataParsed[i] =dataParsed[i] +singleParsed[i] +"\n" ;
// MainActivity.compte[i]=dataParsed[i];
// singleParsed[i] = "fullname:" + JO.get("fullname") + "\n"+
// "accountnumber:" + JO.get("accountnumber") + "\n"+
// "rib:" + JO.get("rib") + "\n"+
// "iban:" + JO.get("iban") + "\n"+
// "name:" + JO.get("name") + "\n"+
//"balance:" + JO.get("balance") + "\n";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
for(int i =0 ;i <2; i++) {
// MainActivity.data.setText(this.d[i]);
}
}
//Authorization Bearer
my MainActivity
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
public static String jsonArray;
private RequestQueue mQueue;
ImageView imageView2;
public static TextView textView_type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQueue = Volley.newRequestQueue(this);
click = (Button) findViewById(R.id.button_parse);
data = (TextView) findViewById(R.id.text_view_result);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.listeview);
CustomAdaptercompte customAdapter=new CustomAdaptercompte();
ListView listeview=(ListView) findViewById(R.id.liste);
listeview.setAdapter(customAdapter);
fetchcompte process = new fetchcompte();
process.execute();
}
});
}
public class CustomAdaptercompte extends BaseAdapter {
#Override
public int getCount() {
return 2;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup viewgrp) {
View view = getLayoutInflater().inflate(R.layout.customlayout,null);
imageView2 = (ImageView) view.findViewById(R.id.imageView2);
textView_type =(TextView) view.findViewById(R.id.textView_type);
imageView2.setImageResource(R.drawable.compte);
textView_type.setText(dataParsed[i]);
return view;
}
}
}
The mistake that you have made is that you assume that
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
will automatically just be the dataParsed Variable you need. What that line does is that it gets the default value of dataParsed (from a default fetchcompte instance). Since you make another instance of a fetchcompte object [called process] (which you are using to populate its dataParsed variable) simply access the dataParsed variable of that instance.
So instead of using:
textView_type.setText(dataParsed[i]);
You can use:
textView_type.setText(process.dataParsed[i]);
But to do this you will need to somehow access the process variable in your adapter class.

How to add recylerview2 inside recylerview1 by clicking listitem of recyclerview1?

I have image like this for example:
Recylerview2 inside Recylerview1
In this case:
If I click on the number 1 of list item, then recylerview2 will appear below a number 1
So my question is:
How can i do that? and this is my code.
Ive this code inside onBindViewHolder inside adapter.
fItemsHolder.mLinearReply.setVisibility(View.GONE);
if (item.getName2() != null) {
fItemsHolder.mHiddenComment.setText(item.getName2()+": "+item.getComment2());
fItemsHolder.feedImageView.setVisibility(View.VISIBLE);
int jComment = Integer.parseInt(item.getJumlahComment().toString());
if( jComment > 0){
fItemsHolder.mHiddenComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView = new RecyclerView(mContext);
getListViewComments(item.getUserid(), item.getId(),fItemsHolder,i, commentItems, adapter, mRecyclerView);
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView.setAdapter(adapter);
}
});
}
} else {
fItemsHolder.mHiddenComment.setVisibility(View.GONE);
fItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
}
And this is my asynctask:
private void getListViewComments(final String userid, String id_note,final feedItemsHolder feedItemsHolder, int i, final List<CommentModel> commentItems, final NoteCommentListAdapter adapter, final RecyclerView mRecyclerView) {
class ambilComment extends AsyncTask<String, Void, String> {
ProgressDialog loading;
com.android.personalRoom.asynctask.profileSaveDescription profileSaveDescription = new profileSaveDescription();
String result = "";
InputStream inputStream = null;
#Override
protected void onPreExecute() {
feedItemsHolder.mLoading.setVisibility(View.GONE);
feedItemsHolder.mHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLoading.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("userid", params[0]);
data.put("id_note", params[1]);
String result = profileSaveDescription.sendPostRequest(URL_LIST_VIEW_COMMENT,data);
return result;
}
protected void onPostExecute(String s) {
JSONArray dataJsonArr = null;
if(s.equals(null)){
Toast.makeText(mContext, "Internet Problem.", Toast.LENGTH_SHORT).show();
Log.w("notakomen", "notakomen: "+s);
}else{
Log.w("notakomen", "notakomen: "+s);
try{
JSONObject json = new JSONObject(s);
String id_note = json.getString("id_note");
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String id_comment = c.getString("id_comment");
String uid = c.getString("userid");
String profile_name = c.getString("profile_name");
String profile_photo = c.getString("profile_photo");
String amount_of_like = c.getString("amount_of_like");
String amount_of_dislike = c.getString("amount_of_dislike");
String amount_of_comment = c.getString("amount_of_comment");
String content_comment = c.getString("content_comment");
String tgl_comment = c.getString("tgl_comment");
String parent_id = c.getString("parent_id");
Log.e(TAG, "id_comment: " + id_comment
+ ", uid: " + uid
+ ", profile_name: " + profile_name
+ ", profile_photo: " + profile_photo
+ ", amount_of_comment: " + amount_of_comment
+ ", tgl_comment: " + tgl_comment);
CommentModel citem = new CommentModel();
citem.setId_note(id_note);
citem.setId_comment(id_comment);
citem.setUserid(uid);
citem.setProfileName(profile_name);
String pPhoto = c.isNull("profile_photo") ? null : c.getString("profile_photo");
citem.setProfile_photo(pPhoto);
citem.setJumlahLove(amount_of_like);
citem.setJumlahNix(amount_of_dislike);
citem.setJumlahComment(amount_of_comment);
citem.setContent_comment(content_comment);
citem.setTimeStamp(tgl_comment);
String prntID = c.isNull("parent_id") ? null : c.getString("parent_id");
citem.setParent_id(prntID);
citem.setLevel(level);
commentItems.add(citem);
feedItemsHolder.mNameReply.setText(profile_name);
}
adapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
Log.w("getListNotesComment", "exception");
}
feedItemsHolder.mLoading.setVisibility(View.GONE);
feedItemsHolder.mLinearReply.setVisibility(View.VISIBLE);
}
/* iH.mHiddenComment.setText("");*/
}
}
ambilComment ru = new ambilComment();
ru.execute(userid, id_note);
}
Try using this library: android-advancedrecyclerview
Check this example on how to use expandable recyclerview using this lib.
To use it, add the lib to your project by adding a dependency for it in the gradle.build file as:
dependencies {
compile ('com.h6ah4i.android.widget.advrecyclerview:advrecyclerview:0.9.1#aar'){
transitive=true
}
}

Android: sort by date in the JSON data

I am new to Android. I'm trying to sort by the date in the JSON data, but nothing works. I'm not even getting an error. I've tried so many different ways, but its not working.
I did a lot of searching but could not figure out how to implement this. How can I sort this by the days column? Thank you in advance.
Here's my code
public class ParseJSONTask extends AsyncTask< Void , Void , Void > {
public Handler handler = new Handler();
public Activity act = null;
private static String TAG_SERVICES = "services";
private static String TAG_ID = "id";
private static String TAG_COMMAND = "command";
private static String TAG_DAYS = "days";
private static String TAG_HOURS = "hours";
private static String TAG_OSMS = "osms";
private static String TAG_ISMS = "isms";
private static String TAG_TIMEOUT = "timeout";
public String SMS_SENT = "SMS Gönderildi";
public String SMS_DELIVERED = "SMS İletildi";
public String serviceString = "";
ArrayList<ServiceData> services;
#Override
public void onPreExecute() {
super.onPreExecute();
services = new ArrayList<ServiceData>();
}
#Override
public Void doInBackground(Void... params) {
WebServiceHandler webServiceHandler = new WebServiceHandler();
String JsonStr = webServiceHandler.getJSONData("http://jsonblob.com/55e34310e4b01190df36e861");
try {
JSONObject jsonObject = new JSONObject(JsonStr);
final JSONArray contactsJSON = jsonObject.getJSONArray(TAG_SERVICES);
for (int i = 0; i < contactsJSON.length(); i++) {
ServiceData aServiceData = new ServiceData();
//json parse istedimiz veriyi kullanabiliriz.
JSONObject serviceObject = contactsJSON.getJSONObject(i);
aServiceData.id = serviceObject.getString(TAG_ID);
aServiceData.command = serviceObject.getString(TAG_COMMAND);
aServiceData.days = serviceObject.getString(TAG_DAYS);
aServiceData.hours = serviceObject.getString(TAG_HOURS);
aServiceData.osms = serviceObject.getString(TAG_OSMS);
aServiceData.isms = serviceObject.getString(TAG_ISMS);
aServiceData.timeout = serviceObject.getString(TAG_TIMEOUT);
String input = aServiceData.days + " " + aServiceData.hours;
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(input);
long milliseconds = date.getTime();
final long millisecondsFromNow = milliseconds - (new Date()).getTime();
aServiceData.milliseconds = milliseconds;
services.add(aServiceData);
if(millisecondsFromNow > 0) {
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Thread.sleep(Integer.parseInt(aServiceData.timeout) * 60000);
}
//Timeout aşağı kısımda sürelendirilecek
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String serviceString = "";
for (ServiceData aServiceData:services){
serviceString+=aServiceData.toString();
}
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
// here is sorted data
for (ServiceData aServiceData : services) {
// move DateSendSMS here. above you can add additional logic about millis
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Log.d("+++++", aServiceData.toString());
}
}
}
ServiceData Class:
public static class ServiceData {
public long milliseconds;
public String id = "";
public String command = "";
public String days = "";
public String hours = "";
public String osms = "";
public String isms = "";
public String timeout = "";
#Override
public String toString() {
return id + ", " + command + ", " + days + ", " + hours + ", " + osms + ", " + isms
+ ", " + timeout + "\n \n ";
}
}
Add time field to ServiceData class
ServiceDate {
...
long milliseconds;
...
}
Fill this field in for loop:
long milliseconds = date.getTime();
aServiceData.milliseconds = milliseconds;
Sort services in onPostExecute
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
I am not sure you can directly sort Json Data (I dont know weather there is a library that will actually do it - if so go for it). I Suggest you to put all the ServiceData into a collection (Which you do at the moment) and then Sort it.
You can write your own sorting algorithm or you can use a Java Collections library to do the sorting by implimention Comparable on your ServiceData class or using a Comparable and them you can use Colletions.sort() to sort your list.
Here is a good tutorial.

Parsing xml data on Android

What I wanted to have is to collect all the results in an ArrayList and iterate in that arraylist and display the result but when I try to run the code below, it only return one element...
I have 3 classes...
public class XMLDataCollected {
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> vicinities = new ArrayList<String>();
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> lats = new ArrayList<String>();
ArrayList<String> longs = new ArrayList<String>();
String name = null;
String vicinity = null;
String type = null;
String lat = null;
String longi = null;
public ArrayList<String> getName() {
return names;
}
public void setName(String name) {
this.names.add(name);
this.name = name;
Log.i("This is the name: ", name + "size: " + names.size());
}
public ArrayList<String> getVicinity() {
return vicinities;
}
public void setVicinity(String vicinity) {
this.vicinities.add(vicinity);
this.vicinity = vicinity;
Log.i("This is the vicinity: ", vicinity);
}
public ArrayList<String> getType() {
return types;
}
public void setType(String type) {
this.types.add(type);
this.type = type;
Log.i("This is the type: ", type);
}
public ArrayList<String> getLat() {
return lats;
}
public void setLat(String lat) {
this.lats.add(lat);
this.lat = lat;
Log.i("This is the latitude: ", lat);
}
public ArrayList<String> getLongi() {
return longs;
}
public void setLongi(String longi) {
this.longs.add(longi);
this.longi = longi;
Log.i("This is the longitude: ", longi);
}
public String populate(){
StringBuilder sb = new StringBuilder();
sb.append(getName());
sb.append(getVicinity());
sb.append(getType());
sb.append(getLat());
sb.append(getLongi());
return sb.toString();
}
2.
public class HandlingXMLStuff extends DefaultHandler {
String elementValue = null;
Boolean elementOn = false;
XMLDataCollected data;
public ArrayList<String> getData() {
return data.getName();
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
elementOn = true;
if (localName.equals("result")) {
data = new XMLDataCollected();
} else if (localName.equals("CD")) {
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("name"))
data.setName(elementValue);
else if (localName.equalsIgnoreCase("vicinity"))
data.setVicinity(elementValue);
else if (localName.equalsIgnoreCase("type"))
data.setType(elementValue);
else if (localName.equalsIgnoreCase("lat"))
data.setLat(elementValue);
else if (localName.equalsIgnoreCase("lng"))
data.setLongi(elementValue);
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
3.
public class XMLParsingActivity extends Activity implements OnClickListener {
static final String baseURL = "http://www.google.com/ig/api?weather=";
static final String test = "";
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bone = (Button) findViewById(R.id.btnone);
tv = (TextView) findViewById(R.id.tvWeather);
bone.setOnClickListener(this);
}
public String buildURL(int lat, int longi){
String url = "";
return url;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try{
URL website = new URL(test);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
HandlingXMLStuff doingWork = new HandlingXMLStuff();
XMLDataCollected xdc = new XMLDataCollected();
xr.setContentHandler(doingWork);
xr.parse(new InputSource(website.openStream()));
StringBuilder sb = new StringBuilder();
String name = null;
for(int index = 0; index < doingWork.getData().size(); index++){
sb.append(doingWork.getData().get(index));
Log.i("test","" + index);
}
// tv.setText("Name: " + name + "\n" + "Vicinity: " + vicinity + "\n" + "Type: " + type + "\n "
// + "Latitude: " + lat + "\n " + "Longitude: " + longi
// );
tv.setText("The size: " + sb);
}catch(Exception ex){
tv.setText("Error" + ex.toString());
}
}
}
This is the sample XML file...
<result>
<name>Zaaffran Restaurant - BBQ and GRILL, Darling Harbour</name>
<vicinity>Harbourside Centre 10 Darling Drive, Darling Harbour, Sydney</vicinity>
<type>restaurant</type>
<type>food</type>
<type>establishment</type>
<geometry>
<location>
<lat>-33.8719830</lat>
<lng>151.1990860</lng>
</location>
</geometry>
<rating>3.9</rating>
</result>
What I want to achieve here is to iterate in the result but the result arraylist has only one element...please help me...
This should help you
http://p-xr.com/android-tutorial-how-to-parseread-xml-data-into-android-listview/
EDIT Also I recommend using the generic LIST <T> instead of ArrayList<T> as follows
List<String> names = new ArrayList<String>();
....
....
for code optimization as the latter ArrayList<String> has memory occupancy. Its not a big issue but optimization is the fundamental step to check the magnitude of efficiency (with respect to time duration and memory) of a program.

Categories

Resources