Android: sort by date in the JSON data - android

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.

Related

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, Comparator sort wrong

I have a Comparator to sort by 3 values:
ORDER_BY_Points
ORDER_BY_Gdif // goals difference
ORDER_BY_Goals
First I get a array from a json string. I send the array to StandingsSort.ORDER_BY_RULES
Arrays.sort(addressArray, StandingsSort.ORDER_BY_RULES);
Here is my code:
static final Comparator<Standings> ORDER_BY_Points = new Comparator<Standings>() {
public int compare(Standings a1, Standings a2) {
return a1.points.compareTo(a2.points);
}
};
static final Comparator<Standings> ORDER_BY_Gdif = new Comparator<Standings>() {
public int compare(Standings a1, Standings a2) {
return a1.Gdif.compareTo(a2.Gdif);
}
};
static final Comparator<Standings> ORDER_BY_Goals = new Comparator<Standings>() {
public int compare(Standings a1, Standings a2) {
return a1.goalsP.compareTo(a2.goalsP);
}
};
static final Comparator<Standings> ORDER_BY_RULES = new Comparator<Standings>() {
public int compare(Standings a1, Standings a2) {
int i = ORDER_BY_Points.compare(a1,a2);
if(i == 0){
i = ORDER_BY_Gdif.compare(a1,a2);
if(i == 0){
i = ORDER_BY_Goals.compare(a1,a2);
}
}
return i;
}
};
class Standings {
String teamName;
String goalsP;
String goalsM;
String Gdif;
String points;
#Override
public String toString() {
return "" + teamName + "," + goalsP + ":" + goalsM + "," + Gdif + "," + points + "";
}
public Standings(String teamName, String goalsP,
String goalsM, String Gdif, String points) {
super();
this.teamName = teamName;
this.goalsP = goalsP;
this.goalsM = goalsM;
this.Gdif = Gdif;
this.points = points;
}
}
But the result is not OK! Here is the result
Name, Goals, GDif, Points
Team,11:9,2,10
Team,5:3,2,10
Team,9:2,7,11
Team,0:6,-6,2
Team,3:9,-6,2
Team,6:9,-3,3
Team,8:13,-5,3
Team,8:9,-1,5
Team,8:11,-3,5
Team,8:7,1,5
Why does the Comparator sort wrong?
Since you store the points as Strings, "10" comes before "2", "3", and "5". If you want to compare these in order by the numerical value, you need to convert them into ints first.
Similarly, Gdif and Goals are compared as Strings which is probably not what you want.

Android read contacts(and details) seems very slow

I use the following code to read each contacts along with their details.
private static final String[] PROJECTION =
{
Data._ID,
Data.MIMETYPE,
Data.DATA1,
Data.DATA2,
Data.DATA3,
Data.DATA4,
Data.DATA5,
Data.DATA6,
Data.DATA7,
Data.DATA8,
Data.DATA9,
Data.DATA10,
Data.DATA11,
Data.DATA12,
Data.DATA13,
Data.DATA14,
Data.DATA15
};
private static final String SELECTION = Data.LOOKUP_KEY + " = ?";
private String[] mSelectionArgs = { "" };
private static final String SORT_ORDER = Data.MIMETYPE;
private static final int MIME_TYPE_INDEX = 1;
private static final int DISPLAY_NAME_INDEX = 3;//data2
private static final int GIVEN_NAME_INDEX = 3;//data2
private static final int FAMILY_NAME_INDEX = 4;//data3
private static final int MIDDLE_NAME_INDEX = 6;//data5
private static final int ORGANIZATION_INDEX = 2;//data2
private static final int PHONE_TYPE_INDEX = 3;//data2
private static final int PHONE_LABEL_INDEX = 4;//data3
private static final int PHONE_NUMBER_INDEX = 2;//data1
private static final int EMAIL_TYPE_INDEX = 3;//data2
private static final int EMAIL_LABEL_INDEX = 4;//data1
private static final int EMAIL_INDEX = 2;//data1
private byte[] createJsonData(ArrayList<String> selected) throws JSONException, IOException{
Log.d("SynchContactActivity", "Time 1: " + java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
int current = 0;
final String messagePrep = getResources().getString(R.string.progress_message_prep);
final String messageCompress = getResources().getString(R.string.progress_message_compress);
final String messageUpload = getResources().getString(R.string.progress_message_upload);
if(selected == null ){
selected = getContacts();
}
final int count = selected.size();
mHandler.post(new Runnable() {
#Override
public void run() {
if(mProgressDialog != null){
mProgressDialog.setMax(count);
mProgressDialog.setMessage(messagePrep);
}
}
});
updateProgress(current);
JSONObject root = new JSONObject();
JSONArray contactsArray = new JSONArray();
JSONObject contactJSON, phoneJSON, emailJSON;
JSONArray phonesArray,emailsArray;
String name, lastName, middleName,organization;
for (String key : selected) {
contactJSON = new JSONObject();
phonesArray = new JSONArray();
emailsArray = new JSONArray();
mSelectionArgs[0] = key;
//Cursor details = managedQuery(Data.CONTENT_URI, PROJECTION, SELECTION, mSelectionArgs, SORT_ORDER);
Cursor details = getApplicationContext().getContentResolver().query(Data.CONTENT_URI, PROJECTION, SELECTION, mSelectionArgs, SORT_ORDER);
//initialize null variables
name = null;
lastName = null;
middleName = null;
organization = null;
while(details.moveToNext()){
String mimeType = details.getString(MIME_TYPE_INDEX);
if(mimeType.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)){
name = details.getString(GIVEN_NAME_INDEX);
lastName = details.getString(FAMILY_NAME_INDEX);
middleName = details.getString(MIDDLE_NAME_INDEX);
}
else if(mimeType.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
organization = details.getString(ORGANIZATION_INDEX);
}
else if(mimeType.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
phoneJSON = new JSONObject();
String phoneNumber = details.getString(PHONE_NUMBER_INDEX);
int type = details.getInt(PHONE_TYPE_INDEX);
String typeLabel = phoneTypeMap.get(String.valueOf(type));
if (typeLabel == null) {
typeLabel = details.getString(PHONE_LABEL_INDEX);
}
phoneJSON.put("ptype", typeLabel);
phoneJSON.put("number", phoneNumber);
phonesArray.put(phoneJSON);
}
else if(mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)){
emailJSON = new JSONObject();
String email = details.getString(EMAIL_INDEX);
int type = details.getInt(EMAIL_TYPE_INDEX);
String typeLabel = emailTypeMap.get(String.valueOf(type));
if (typeLabel == null) {
typeLabel = details.getString(EMAIL_LABEL_INDEX);
}
emailJSON.put("etype", typeLabel);
emailJSON.put("address",email);
emailsArray.put(emailJSON);
}
}
contactJSON.put("firstname", name==null?"null":name);
contactJSON.put("middlename", middleName==null?"null":middleName);
contactJSON.put("lastname", lastName==null?"null":lastName);
contactJSON.put("organization", organization==null?"null":organization);
contactJSON.put("phones", phonesArray);
contactJSON.put("emails", emailsArray);
contactsArray.put(contactJSON);
details.close();
++current;
updateProgress(current);
}
root.put("contacts", contactsArray);
Log.d("SynchContactActivity", "Time 1: " + java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
mHandler.post(new Runnable() {
#Override
public void run() {
if(mProgressDialog != null){
mProgressDialog.setMessage(messageCompress);
}
}
});
// to compress
String json_doc = root.toString();
byte[] compressed = compress(json_doc);
mHandler.post(new Runnable() {
#Override
public void run() {
if(mProgressDialog != null){
mProgressDialog.setMessage(messageUpload);
}
}
});
return compressed;
}
This code is too slow - that reads 3-4 contacts per second on average. Is this normal or can be optimized?
I think projection might be a good candidate to be optimized but I'm not sure.
Thanks in advance.
It's hard for me to tell exactly what you're trying to do, but it looks like you're trying to read data from the Contacts Provider and send it to a server using JSON. I suggest you look at the ContactsContract.RawContacts.Entity table, which contains all the data you're probably looking for without the mess of trying to figure out the MIME type of the DATA row you've just retrieved. You're certainly slowing down your app by getting the entire contents of the DATA row.
In addition, you should use a SyncAdapter to do this work. See Transferring Data Using Sync Adapters
Reading contacts can be made in 2-5 seconds. See the example app here
Source code attached

How to retrieve RSS FEED from Yahoo weather

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));
}
}

Categories

Resources