Related
Explanation:I have json.In which, i have object namely matches.Inside the matches object i have lot of objects.I mean data->season->matches->object1,2,3 so on.
This objects are dynamic it's not fixed at the run-time.I tried to parse the matches object.
Here is my json data
Now i tried to parse this file using my url.I was used a volley network library to parse the json file from server.
Here is my code to parse the json and get the response
public class SeriesActivity extends AppCompatActivity {
Toolbar toolbar;
String series_key = "";
String url = "";
String access_token = "";
FrameLayout frameLayout;
List<SeriesMatches> series_header;
HashMap<SeriesMatches, List<SeriesMatches>> series_child;
String winner_team = "";
String overs = "";
String wickets_now = "";
String now_runs = "";
String now_bat_team = "";
String fullScore = "";
String team_name = "";
String[] over_parts;
ExpandableListView expListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
frameLayout = (FrameLayout) findViewById(R.id.adbar);
new AddLoader(getApplicationContext()).LoadAds(frameLayout);
SharedPreferences sharedPreferences = this.getSharedPreferences("SaveTime", MODE_PRIVATE);
access_token = sharedPreferences.getString("accessToken", null);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
Intent intent = getIntent();
series_key = intent.getStringExtra("series_key");
url = "https://api.litzscore.com/rest/v2/season/" + series_key + "/?access_token=" + access_token + "&card_type=summary_card";
if (!Utils.isNetworkConnected(this)) {
dialog_popup();
} else {
getSeriesMatches();
}
}
public void getSeriesMatches() {
String str_req = "getSeries";
StringRequest matches_req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
try {
JSONObject object = new JSONObject(response);
if (!object.getBoolean("status") || object.getString("status_code").equals("403")) {
// DialogAbandoned abandoned=new DialogAbandoned(getApplicationContext());
// abandoned.setDialog("Series","Data Coming soon...");
} else {
series_header = new ArrayList<>();
series_child = new HashMap<>();
if (object.has("data") && !object.isNull("data")) {
JSONObject data = object.getJSONObject("data");
JSONObject season;
JSONObject matches;
if (data.has("season") && !data.isNull("season")) {
season = data.getJSONObject("season");
if (season.has("matches") && !season.isNull("matches")) {
matches = season.getJSONObject("matches");
JSONArray matches_arr = matches.names();
JSONObject matches_obj;
for (int i = 0; i < matches_arr.length(); i++) {
SeriesMatches s_matches = new SeriesMatches();
matches_obj = matches.getJSONObject(matches_arr.getString(i));
JSONObject teams = matches_obj.getJSONObject("teams");
JSONObject team_a = teams.getJSONObject("a");
JSONObject team_b = teams.getJSONObject("b");
JSONObject start_date = matches_obj.getJSONObject("start_date");
s_matches.setRealted_name(matches_obj.getString("related_name"));
series_header.add(s_matches);
if (!matches_obj.isNull("msgs") && matches_obj.has("msgs")) {
JSONObject msgs = matches_obj.getJSONObject("msgs");
winner_team = "";
if (msgs.has("info")) {
winner_team = msgs.getString("info");
}
}
JSONObject now;
now_bat_team = "";
now_runs = "";
wickets_now = "";
overs = "";
if (matches_obj.has("now") && !matches_obj.isNull("now")) {
now = matches_obj.getJSONObject("now");
if (now.has("batting_team")) {
now_bat_team = now.getString("batting_team");
}
if (now.has("runs")) {
if (now.getString("runs").equals("0")) {
now_runs = "0";
} else {
now_runs = now.getString("runs");
}
}
if (now.has("runs_str") && !now.isNull("runs_str")) {
if (now.getString("runs_str").equals("0")) {
overs = "0";
} else {
if (now.getString("runs_str").equals("null")) {
overs = "0";
} else {
over_parts = now.getString("runs_str").split(" ");
overs = over_parts[2];
}
}
}
if (now.has("wicket")) {
if (now.getString("wicket").equals("0")) {
wickets_now = "0";
} else {
wickets_now = now.getString("wicket");
}
}
}
JSONArray team_arr = teams.names();
JSONObject team_obj;
for (int a = 0; a < team_arr.length(); a++) {
if (now_bat_team.equals(team_arr.getString(a))) {
team_obj = teams.getJSONObject(team_arr.getString(a));
team_name = "";
if (team_obj.has("short_name") && !team_obj.isNull("short_name")) {
team_name = team_obj.getString("short_name");
}
}
}
if (matches_obj.has("status_overview") && !matches_obj.isNull("status_overview")) {
if (matches_obj.getString("status_overview").equals("abandoned") || matches_obj.getString("status_overview").equals("canceled")) {
fullScore = "";
} else {
fullScore = team_name + " - " + now_runs + "/" + wickets_now + " (" + overs + " ovr)";
}
}
SeriesMatches s2 = new SeriesMatches();
s2.setTeam_Aname(team_a.getString("short_name"));
s2.setTemm_Akey(team_a.getString("key"));
s2.setTeam_Bname(team_b.getString("short_name"));
s2.setTeam_Bkey(team_b.getString("key"));
s2.setStatus(matches_obj.getString("status"));
s2.setDate(start_date.getString("iso"));
s2.setVenue(matches_obj.getString("venue"));
s2.setMsgs(winner_team);
s2.setScore(fullScore);
s2.setMom(matches_obj.getString("man_of_match"));
List<SeriesMatches> matches_info = new ArrayList<>();
matches_info.add(s2);
series_child.put(series_header.get(i), matches_info);
}
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
ExpandedListAdapter adapter = new ExpandedListAdapter(getApplicationContext(), series_header, series_child);
expListView.setAdapter(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
dialog_popup();
} else if (error instanceof AuthFailureError) {
dialog_popup();
} else if (error instanceof ServerError) {
dialog_popup();
} else if (error instanceof NetworkError) {
dialog_popup();
} else if (error instanceof ParseError) {
dialog_popup();
}
}
});
AppController.getInstance().addToRequestQueue(matches_req, str_req);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Here is my Expnadedlistview
public class ExpandedListAdapter extends BaseExpandableListAdapter{
private Context context;
private List<SeriesMatches> series_header;
private HashMap<SeriesMatches,List<SeriesMatches>> series_child;
private Typeface tf;
public ExpandedListAdapter(Context context,List<SeriesMatches> series_header,HashMap<SeriesMatches,List<SeriesMatches>> series_child){
this.context=context;
this.series_header=series_header;
this.series_child=series_child;
}
#Override
public int getGroupCount() {
return this.series_header.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return this.series_child.get(this.series_header.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return this.series_header.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return this.series_child.get(this.series_header.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.list_group,null);
}
TextView text_group=(TextView)convertView.findViewById(R.id.lblListHeader);
SeriesMatches s=series_header.get(groupPosition);
text_group.setText(s.getRealted_name());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.list_child,null);
tf = Typeface.createFromAsset(convertView.getResources().getAssets(), "Roboto-Regular.ttf");
}
TextView teamA=(TextView)convertView.findViewById(R.id.txt_one_country_name);
TextView teamB=(TextView)convertView.findViewById(R.id.txt_two_country_name);
TextView txt_venue=(TextView)convertView.findViewById(R.id.venue);
TextView txtTimeIST=(TextView)convertView.findViewById(R.id.txt_timeist);
TextView txtTimeGMT=(TextView)convertView.findViewById(R.id.txt_timegmt);
TextView txtDate=(TextView)convertView.findViewById(R.id.txt_date);
ImageView team_one_flag_icon=(ImageView)convertView.findViewById(R.id.team_one_flag_icon);
ImageView team_two_flag_icon=(ImageView)convertView.findViewById(R.id.team_two_flag_icon);
SeriesMatches s1=series_child.get(series_header.get(groupPosition)).get(childPosition);
String team_a_key=s1.getTemm_Akey();
String team_b_key=s1.getTeam_Bkey();
teamA.setText(s1.getTeam_Aname());
teamB.setText(s1.getTeam_Bname());
if(team_a_key.equals("ind")) {
team_one_flag_icon.setImageResource(R.drawable.ind);
}
else if(team_a_key.equals("omn")){
team_one_flag_icon.setImageResource(R.drawable.omn);
}
else if(team_a_key.equals("afg")) {
team_one_flag_icon.setImageResource(R.drawable.afg);
} else if(team_a_key.equals("aus")) {
team_one_flag_icon.setImageResource(R.drawable.aus);
} else if(team_a_key.equals("ban")) {
team_one_flag_icon.setImageResource(R.drawable.ban);
} else if(team_a_key.equals("eng")) {
team_one_flag_icon.setImageResource(R.drawable.eng);
} else if(team_a_key.equals("hkg")) {
team_one_flag_icon.setImageResource(R.drawable.hkg);
} else if(team_a_key.equals("ire")) {
team_one_flag_icon.setImageResource(R.drawable.ire);
} else if(team_a_key.equals("nl")) {
team_one_flag_icon.setImageResource(R.drawable.nl);
} else if(team_a_key.equals("nz")) {
team_one_flag_icon.setImageResource(R.drawable.nz);
} else if(team_a_key.equals("pak")) {
team_one_flag_icon.setImageResource(R.drawable.pak);
} else if(team_a_key.equals("rsa")) {
team_one_flag_icon.setImageResource(R.drawable.rsa);
}else if (team_a_key.equalsIgnoreCase("sl")) {
team_one_flag_icon.setImageResource(R.drawable.sl);
} else if (team_a_key.equals("uae")) {
team_one_flag_icon.setImageResource(R.drawable.uae);
} else if (team_a_key.equals("wi")) {
team_one_flag_icon.setImageResource(R.drawable.wi);
} else if (team_a_key.equals("zim")) {
team_one_flag_icon.setImageResource(R.drawable.zim);
} else if(team_a_key.equals("sct")) {
team_one_flag_icon.setImageResource(R.drawable.sct);
////////// IPL Team ///////////
} else if(team_a_key.equals("dd")) {
team_one_flag_icon.setImageResource(R.drawable.dd);
} else if(team_a_key.equals("kkr")) {
team_one_flag_icon.setImageResource(R.drawable.kkr);
} else if(team_a_key.equals("mi")) {
team_one_flag_icon.setImageResource(R.drawable.mi);
} else if(team_a_key.equals("srh")) {
team_one_flag_icon.setImageResource(R.drawable.sh);
} else if(team_a_key.equals("kxip")) {
team_one_flag_icon.setImageResource(R.drawable.kxip);
} else if(team_a_key.equals("rcb")) {
team_one_flag_icon.setImageResource(R.drawable.rcb);
} else if(team_a_key.equals("rps")) {
team_one_flag_icon.setImageResource(R.drawable.rps);
} else if(team_a_key.equals("gl")) {
team_one_flag_icon.setImageResource(R.drawable.gl);
} else {
team_one_flag_icon.setImageResource(R.drawable.dft);
}
//for B TEAM
if(team_b_key.equals("ind")) {
team_two_flag_icon.setImageResource(R.drawable.ind);
}
else if(team_b_key.equals("omn")){
team_two_flag_icon.setImageResource(R.drawable.omn);
}
else if(team_b_key.equals("afg")) {
team_two_flag_icon.setImageResource(R.drawable.afg);
} else if(team_b_key.equals("aus")) {
team_two_flag_icon.setImageResource(R.drawable.aus);
} else if(team_b_key.equals("ban")) {
team_two_flag_icon.setImageResource(R.drawable.ban);
} else if(team_b_key.equals("eng")) {
team_two_flag_icon.setImageResource(R.drawable.eng);
} else if(team_b_key.equals("hkg")) {
team_two_flag_icon.setImageResource(R.drawable.hkg);
} else if(team_b_key.equals("ire")) {
team_two_flag_icon.setImageResource(R.drawable.ire);
} else if(team_b_key.equals("nl")) {
team_two_flag_icon.setImageResource(R.drawable.nl);
} else if(team_b_key.equals("nz")) {
team_two_flag_icon.setImageResource(R.drawable.nz);
} else if(team_b_key.equals("pak")) {
team_two_flag_icon.setImageResource(R.drawable.pak);
} else if(team_b_key.equals("rsa")) {
team_two_flag_icon.setImageResource(R.drawable.rsa);
}else if (team_b_key.equalsIgnoreCase("sl")) {
team_two_flag_icon.setImageResource(R.drawable.sl);
} else if (team_b_key.equals("uae")) {
team_two_flag_icon.setImageResource(R.drawable.uae);
} else if (team_b_key.equals("wi")) {
team_two_flag_icon.setImageResource(R.drawable.wi);
} else if (team_b_key.equals("zim")) {
team_two_flag_icon.setImageResource(R.drawable.zim);
} else if(team_b_key.equals("sct")) {
team_two_flag_icon.setImageResource(R.drawable.sct);
////////// IPL ///////////
} else if(team_b_key.equals("dd")) {
team_two_flag_icon.setImageResource(R.drawable.dd);
} else if(team_b_key.equals("kkr")) {
team_two_flag_icon.setImageResource(R.drawable.kkr);
} else if(team_b_key.equals("mi")) {
team_two_flag_icon.setImageResource(R.drawable.mi);
} else if(team_b_key.equals("srh")) {
team_two_flag_icon.setImageResource(R.drawable.sh);
} else if(team_b_key.equals("kxip")) {
team_two_flag_icon.setImageResource(R.drawable.kxip);
} else if(team_b_key.equals("rcb")) {
team_two_flag_icon.setImageResource(R.drawable.rcb);
} else if(team_b_key.equals("rps")) {
team_two_flag_icon.setImageResource(R.drawable.rps);
} else if(team_b_key.equals("gl")) {
team_two_flag_icon.setImageResource(R.drawable.gl);
} else {
team_two_flag_icon.setImageResource(R.drawable.dft);
}
try {
String[] fullDate;
String fullTime = "";
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'+00':ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("hh:mm a");
String ist=outputFormat.format(utcFormat.parse(s1.getDate()));
Date timestamp;
timestamp = utcFormat.parse(s1.getDate());
fullDate = timestamp.toString().split(" ");
String monthName = fullDate[1];
String Dayname = fullDate[2];
fullTime = fullDate[3];
String[] gmt_fulldate = s1.getDate().split("T");
String gmt_time = gmt_fulldate[1];
String[] gmt_hour_parts = gmt_time.split("\\+");
String finalDate = Dayname + " " + monthName;
String finalTimeIST = ist + " IST | " + gmt_hour_parts[0] + " GMT";
String[] venue_parts=s1.getVenue().split(",");
int length=venue_parts.length;
if(length==1){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
txtTimeGMT.setText(venue_parts[0]);
}
if(length==2){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
txtTimeGMT.setText(venue_parts[0] + "," + venue_parts[1]);
}
if(length==3){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
txtTimeGMT.setText(venue_parts[1] + "," + venue_parts[2]);
}
if(length==4){
txtTimeGMT.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
txtTimeGMT.setText(venue_parts[2] + "," + venue_parts[3]);
}
if(s1.getStatus().equals("notstarted")){
txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
txtDate.setTypeface(tf);
txtDate.setText("Started on " + finalDate);
txtTimeIST.setVisibility(View.VISIBLE);
txtTimeIST.setText(finalTimeIST);
}
if(s1.getStatus().equals("completed")){
txtDate.setTypeface(tf);
txtDate.setText(s1.getScore());
txtDate.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
txtTimeIST.setVisibility(View.VISIBLE);
txtTimeIST.setText(s1.getMsgs());
Log.e("NOTSTARTED","DONE");
txt_venue.setText("MOM : "+s1.getMom().substring(0, 1).toUpperCase() + s1.getMom().substring(1).replace("_", " "));
}
}
catch (ParseException e){
e.printStackTrace();
}
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Problem is i have mobile in which jellybean is installed.In the jellybean or lower of jellybean it's not comes in the order.If same code i ran into lollipop or marshmallow it's comes into the order.Order like
trieseries_2016_g1
trieseries_2016_g2
until trieseries_2016_final
Here is a screenshort of marshmallow
please, help me to solve out this problem.
Here is a sceenshort of jellybean
I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}
I am working on a weather application using weather API where i have to parse using XMLPullParser.When i enter a country name i should receive some values like Humidity,Pressure ,Temperature .In My code when i try to parse The first country name field returns correctly.But i am not able to receive other fields. As i am using getAttributeValue(null,"value") to parse this value and it returns null value..
the XML file is available at XML FILE HERE .
My Code is :
MainAcitivity.java
public class MainActivity extends Activity {
EditText ed1,ed2,ed3,ed4,ed5;
TextView tv2;
private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
private String url2 = "&mode=xml";
private HandleXML obj;
Button b1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
tv2=(TextView)findViewById(R.id.textView2);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
ed4=(EditText)findViewById(R.id.editText4);
ed5=(EditText)findViewById(R.id.editText5);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = ed1.getText().toString();
tv2.setText(url);
String finalUrl = url1 + url + url2;
ed2.setText(finalUrl);
obj = new HandleXML(finalUrl);
obj.fetchXML();
Log.i("MyActivity", "XML Parser View " + obj);
while(obj.parsingComplete);
Log.i("MyActivity", "XML Parsing Complete " + obj.parsingComplete);
ed2.setText(obj.getCountry());
ed3.setText(obj.getTemperature());
ed4.setText(obj.getHumidity());
ed5.setText(obj.getPressure());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
HandleXML.java
public class HandleXML {
private String country = "country";
private String temperature = "temperature";
private String humidity = "humidity";
private String pressure = "pressure";
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXML(String url){
this.urlString = url;
}
public String getCountry(){
return country;
}
public String getTemperature(){
return temperature;
}
public String getHumidity(){
return humidity;
}
public String getPressure(){
return pressure;
}
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
if(name.equals("country")){
country = text;
}
else if(name.equals("humidity")){
humidity = myParser.getAttributeValue(null,"value");
}
else if(name.equals("pressure")){
pressure = myParser.getAttributeValue(null,"value");
}
else if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
else{
}
break;
case XmlPullParser.END_TAG:
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
AndroidMAnifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geevarughese.xmlpars">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Change
case XmlPullParser.TEXT:
to
case XmlPullParser.START_TAG:
it has to be
public void parseXMLAndStoreIt(XmlPullParser myParser) {
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
text = myParser.getText();
if(name.equals("country")){
country = text;
}
else if(name.equals("humidity")){
humidity = myParser.getAttributeValue(null,"value");
}
else if(name.equals("pressure")){
pressure = myParser.getAttributeValue(null,"value");
}
else if(name.equals("temperature")){
temperature = myParser.getAttributeValue(null,"value");
}
else{
}
break;
case XmlPullParser.END_TAG:
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e) {
e.printStackTrace();
}
}
This question already has an answer here:
java.lang.StackOverflowError trying to parse in a AsyncTask
(1 answer)
Closed 8 years ago.
I have been reading this tutorial and came across the problem that it uses a very low api. I got the NetworkOnMainThreadException. I found this answer on stackoverflow which says I have to use AsyncTask.
I have tried using AsyncTask on an empty project working with another tutorial which worked fine.
My problem is that I need to change this project so that I can use it on higher apis. So the thing is AndroidSaxFeedParser is a subclass and AsyncTask is a super class and the error line is on AndroidSaxFeedParser which extends BaseFeedParser and BaseFeedParser extends FeedParser which is an interface(btw I always thought interfaces had to be implemented instead of extended?).
To be more precise the errors are on these line(indicated with --->) :
AndroidSaxFeedParser.java :
try
{
---> Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
}
catch (Exception e)
{
---> throw new RuntimeException(e);
}
MessageList.java :
private void loadFeed(ParserType type)
{
try
{
Log.i("AndroidNews", "ParserType=" + type.name());
FeedParser parser = FeedParserFactory.getParser(type);
long start = System.currentTimeMillis();
---> messages = parser.parse();
long duration = System.currentTimeMillis() - start;
Log.i("AndroidNews", "Parser duration=" + duration);
String xml = writeXml();
Log.i("AndroidNews", xml);
List<String> titles = new ArrayList<String>(messages.size());
for (Message msg : messages)
{
titles.add(msg.getTitle());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row, titles);
this.setListAdapter(adapter);
}
catch (Throwable t)
{
Log.e("AndroidNews", t.getMessage(), t);
}
}
BaseFeedParser.java :
protected InputStream getInputStream()
{
try
{
---> return feedUrl.openConnection().getInputStream();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
So where and how should I use the AsyncTask. (I'm only using the AndroidSaxParser so the other parsers in the tutorial can be ignored).
AndroidSaxFeedParser.java
public class AndroidSaxFeedParser extends BaseFeedParser
{
static final String RSS = "rss";
public AndroidSaxFeedParser(String feedUrl)
{
super(feedUrl);
}
public List<Message> parse()
{
final Message currentMessage = new Message();
RootElement root = new RootElement(RSS);
final List<Message> messages = new ArrayList<Message>();
Element channel = root.getChild(CHANNEL);
Element item = channel.getChild(ITEM);
item.setEndElementListener(new EndElementListener()
{
public void end()
{
messages.add(currentMessage.copy());
}
});
item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener()
{
public void end(String body)
{
currentMessage.setTitle(body);
}
});
item.getChild(LINK).setEndTextElementListener(new EndTextElementListener()
{
public void end(String body)
{
currentMessage.setLink(body);
}
});
item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener()
{
public void end(String body)
{
currentMessage.setDescription(body);
}
});
item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener()
{
public void end(String body)
{
currentMessage.setDate(body);
}
});
try
{
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
}
catch (Exception e)
{
throw new RuntimeException(e);
}
return messages;
}
}
BaseFeedParser.java
public abstract class BaseFeedParser implements FeedParser
{
// names of the XML tags
static final String CHANNEL = "channel";
static final String PUB_DATE = "pubDate";
static final String DESCRIPTION = "description";
static final String LINK = "link";
static final String TITLE = "title";
static final String ITEM = "item";
private final URL feedUrl;
protected BaseFeedParser(String feedUrl)
{
try
{
this.feedUrl = new URL(feedUrl);
}
catch (MalformedURLException e)
{
throw new RuntimeException(e);
}
}
protected InputStream getInputStream()
{
try
{
return feedUrl.openConnection().getInputStream();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
FeedParser.java
public interface FeedParser
{
List<Message> parse();
}
FeedParserFactory.java
public abstract class FeedParserFactory
{
static String feedUrl = "http://example.com/feed/";
public static FeedParser getParser()
{
return getParser(ParserType.ANDROID_SAX);
}
public static FeedParser getParser(ParserType type)
{
switch (type)
{
case SAX:
return new SaxFeedParser(feedUrl);
case DOM:
return new DomFeedParser(feedUrl);
case ANDROID_SAX:
return new AndroidSaxFeedParser(feedUrl);
case XML_PULL:
return new XmlPullFeedParser(feedUrl);
default:
return null;
}
}
}
Message.java
public class Message implements Comparable<Message>
{
static SimpleDateFormat FORMATTER = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss Z", Locale.ENGLISH);
private String title;
private URL link;
private String description;
private Date date;
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title.trim();
}
// getters and setters omitted for brevity
public URL getLink()
{
return link;
}
public void setLink(String link)
{
try
{
this.link = new URL(link);
}
catch (MalformedURLException e)
{
throw new RuntimeException(e);
}
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description.trim();
}
public String getDate()
{
return FORMATTER.format(this.date);
}
public void setDate(String date)
{
// pad the date if necessary
while (!date.endsWith("00"))
{
date += "0";
}
try
{
this.date = FORMATTER.parse(date.trim());
}
catch (ParseException e)
{
throw new RuntimeException(e);
}
}
public Message copy()
{
Message copy = new Message();
copy.title = title;
copy.link = link;
copy.description = description;
copy.date = date;
return copy;
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("Title: ");
sb.append(title);
sb.append('\n');
sb.append("Date: ");
sb.append(this.getDate());
sb.append('\n');
sb.append("Link: ");
sb.append(link);
sb.append('\n');
sb.append("Description: ");
sb.append(description);
return sb.toString();
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((link == null) ? 0 : link.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Message other = (Message) obj;
if (date == null)
{
if (other.date != null)
return false;
}
else if (!date.equals(other.date))
return false;
if (description == null)
{
if (other.description != null)
return false;
}
else if (!description.equals(other.description))
return false;
if (link == null)
{
if (other.link != null)
return false;
}
else if (!link.equals(other.link))
return false;
if (title == null)
{
if (other.title != null)
return false;
}
else if (!title.equals(other.title))
return false;
return true;
}
public int compareTo(Message another)
{
if (another == null)
return 1;
// sort descending, most recent first
return another.date.compareTo(date);
}
}
MessageList.java
public class MessageList extends ListActivity
{
private List<Message> messages;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
loadFeed(ParserType.ANDROID_SAX);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, ParserType.ANDROID_SAX.ordinal(), ParserType.ANDROID_SAX.ordinal(), R.string.android_sax);
menu.add(Menu.NONE, ParserType.SAX.ordinal(), ParserType.SAX.ordinal(), R.string.sax);
menu.add(Menu.NONE, ParserType.DOM.ordinal(), ParserType.DOM.ordinal(), R.string.dom);
menu.add(Menu.NONE, ParserType.XML_PULL.ordinal(), ParserType.XML_PULL.ordinal(), R.string.pull);
return true;
}
#SuppressWarnings("unchecked")
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
super.onMenuItemSelected(featureId, item);
ParserType type = ParserType.values()[item.getItemId()];
ArrayAdapter<String> adapter = (ArrayAdapter<String>) this.getListAdapter();
if (adapter.getCount() > 0)
{
adapter.clear();
}
this.loadFeed(type);
return true;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent viewMessage = new Intent(Intent.ACTION_VIEW, Uri.parse(messages.get(position).getLink().toExternalForm()));
this.startActivity(viewMessage);
}
private void loadFeed(ParserType type)
{
try
{
Log.i("AndroidNews", "ParserType=" + type.name());
FeedParser parser = FeedParserFactory.getParser(type);
long start = System.currentTimeMillis();
messages = parser.parse();
long duration = System.currentTimeMillis() - start;
Log.i("AndroidNews", "Parser duration=" + duration);
String xml = writeXml();
Log.i("AndroidNews", xml);
List<String> titles = new ArrayList<String>(messages.size());
for (Message msg : messages)
{
titles.add(msg.getTitle());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row, titles);
this.setListAdapter(adapter);
}
catch (Throwable t)
{
Log.e("AndroidNews", t.getMessage(), t);
}
}
private String writeXml()
{
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
try
{
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
serializer.startTag("", "messages");
serializer.attribute("", "number", String.valueOf(messages.size()));
for (Message msg : messages)
{
serializer.startTag("", "message");
serializer.attribute("", "date", msg.getDate());
serializer.startTag("", "title");
serializer.text(msg.getTitle());
serializer.endTag("", "title");
serializer.startTag("", "url");
serializer.text(msg.getLink().toExternalForm());
serializer.endTag("", "url");
serializer.startTag("", "body");
serializer.text(msg.getDescription());
serializer.endTag("", "body");
serializer.endTag("", "message");
}
serializer.endTag("", "messages");
serializer.endDocument();
return writer.toString();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
ParserType.java
public enum ParserType
{
SAX, DOM, ANDROID_SAX, XML_PULL;
}
RssHandler.java
public class RssHandler extends DefaultHandler
{
private List<Message> messages;
private Message currentMessage;
private StringBuilder builder;
public List<Message> getMessages()
{
return this.messages;
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException
{
super.characters(ch, start, length);
builder.append(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String name) throws SAXException
{
super.endElement(uri, localName, name);
if (this.currentMessage != null)
{
if (localName.equalsIgnoreCase(TITLE))
{
currentMessage.setTitle(builder.toString());
}
else if (localName.equalsIgnoreCase(LINK))
{
currentMessage.setLink(builder.toString());
}
else if (localName.equalsIgnoreCase(DESCRIPTION))
{
currentMessage.setDescription(builder.toString());
}
else if (localName.equalsIgnoreCase(PUB_DATE))
{
currentMessage.setDate(builder.toString());
}
else if (localName.equalsIgnoreCase(ITEM))
{
messages.add(currentMessage);
}
builder.setLength(0);
}
}
#Override
public void startDocument() throws SAXException
{
super.startDocument();
messages = new ArrayList<Message>();
builder = new StringBuilder();
}
#Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException
{
super.startElement(uri, localName, name, attributes);
if (localName.equalsIgnoreCase(ITEM))
{
this.currentMessage = new Message();
}
}
}
public class ParseAsync extends AsyncTask<Url, Void, ArrayList<FeedItem>> {
#Override
protected ArrayList<FeedItem> doInBackground(Url... params) {
//url as parametr, long time operation
return YourParser.parseFeed(params[0])
}
#Override
protected void onPostExecute(ArrayList<FeedItem> result) {
// this we get result of parser in ui thread
}
}
In ui thread
ParseAsync task = new ParseAsync();
task.execute("www.example.ru/feed.rss")
Answer
I fixed my problem if anyone is interested you can read that question.
i think the problem is because of NetworkOnMainThreadException,So what you want to do is that you need to add StrictMode
Where you use the Async task,so just add this linke on preexectue of the async task
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT>8){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Hope this will solve your problem
I followed a tutorial on how to parse XML(RSS) files on an Android app. Below is my code that is working, but is taking quite long. Am I doing something incorrect or in a way that would slow it down? It takes 7-10 seconds to load 30-35 articles... seemingly way too long, and certainly too long for a user to wait every time they switch sections (which pulls in another feed)
I do have things in place to only pull new data every hour...etc ... but the first time still takes 10 seconds usually, which - by then, the user thinks their app has crashed...etc.
I am doing this in an AsyncTask
I'm not downloading the images at this point
This IS the slow part of the code (not internet, or displaying... etc)
TLDR:
This code is too slow - why?:
package com.mysite.utilities;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class RSSHandler extends DefaultHandler
{
// creats a news item class to hold data within loop
public class NewsItem
{
public String title;
public String subhead;
public String link;
public String byline;
public String description;
public String storytext;
public String cmsstoryid;
public String pubDate;
public String keyword;
public String category;
public String subcategory;
public String slotreference;
public String lastModTime;
public ArrayList<PhotoItem> photos = new ArrayList<PhotoItem>();
#Override
public String toString()
{
return title;
}
}
//creates a photo item class to hold image data within loop
public class PhotoItem
{
public String photoid; //tribs id
public String caption;
public String height;
public String width;
public String photo; //full path to photo
public String thumbnail; //full path to thumbnail
public int articleid;
public String photolastmodified;
#Override
public String toString()
{
return photo;
}
}
//creates instances of classes to be used in loop
private StringBuffer buf; //to hold element characters with loop
private ArrayList<NewsItem> feedItems;
private NewsItem item;
private PhotoItem photoitem;
//initialize variables of whether or not it's within an item (or photo item)
private boolean inItem = false;
private boolean inPhotoItem = false;
//
public ArrayList<NewsItem> getParsedItems() {
return feedItems;
}
//Called at the head of each new element
#Override
public void startElement(String uri, String name, String qName, Attributes atts)
{
//creates an array of news items
if ("channel".equals(name))
{
feedItems = new ArrayList<NewsItem>();
}
//creates a news item and toggles "in news item" to on
else if ("item".equals(name))
{
item = new NewsItem();
inItem = true;
}
//creates a photo item and toggles "in photo item" to on
else if ("image".equals(name))
{
photoitem = new PhotoItem();
inPhotoItem = true;
}
//starts a new string buffer if matches an elemnt we want from news item
else if (
("title".equals(name) ||
"subhead".equals(name) ||
"link".equals(name) ||
"byline".equals(name) ||
"description".equals(name) ||
"storytext".equals(name) ||
"keyword".equals(name) ||
"cmsstoryid".equals(name) ||
"pubDate".equals(name) ||
"category".equals(name) ||
"subcategory".equals(name) ||
"lastModTime".equals(name) ||
"slotreference".equals(name)
)
&& inItem)
{
buf = new StringBuffer();
}
//starts an a new string buffer if it matches an element we want from image item
else if(
("caption".equals(name) ||
"photoid".equals(name) ||
"height".equals(name) ||
"width".equals(name) ||
"photo".equals(name) ||
"photolastmodified".equals(name) ||
"thumbnail".equals(name)
)
&& inPhotoItem)
{
buf = new StringBuffer();
}
}
//Called at the tail of each element end
#Override
public void endElement(String uri, String name, String qName)
{
if ("item".equals(name))
{
feedItems.add(item);
inItem = false;
}
else if ("image".equals(name))
{
try {
item.photos.add(photoitem);
} catch (Exception e) {
System.out.println(e);
}
inPhotoItem = false;
}
else if (inItem)
{
if (inPhotoItem)
{
if ("caption".equals(name)) { photoitem.caption = buf.toString(); }
else if ("photoid".equals(name)) { photoitem.photoid = buf.toString(); }
else if ("height".equals(name)) { photoitem.height = buf.toString(); }
else if ("width".equals(name)) { photoitem.width = buf.toString(); }
else if ("photo".equals(name)) { photoitem.photo = buf.toString(); }
else if ("photolastmodified".equals(name)) { photoitem.photolastmodified = buf.toString(); }
else if ("thumbnail".equals(name)) { photoitem.thumbnail = buf.toString(); }
}
else if ("title".equals(name)) { item.title = buf.toString(); }
else if ("subhead".equals(name)) { item.subhead = buf.toString(); }
else if ("link".equals(name)) { item.link = buf.toString(); }
else if ("byline".equals(name)) { item.byline = buf.toString(); }
else if ("description".equals(name)) { item.description = buf.toString(); }
else if ("storytext".equals(name)) { item.storytext = buf.toString(); }
else if ("keyword".equals(name)) { item.keyword = buf.toString(); }
else if ("cmsstoryid".equals(name)) { item.cmsstoryid = buf.toString(); }
else if ("pubDate".equals(name)) { item.pubDate = buf.toString(); }
else if ("category".equals(name)) { item.category = buf.toString(); }
else if ("subcategory".equals(name)) { item.subcategory = buf.toString(); }
else if ("lastModTime".equals(name)) { item.lastModTime = buf.toString(); }
else if ("slotreference".equals(name)) { item.slotreference = buf.toString(); }
}
else
{
buf = null;
}
}
//Called with character data inside elements
#Override
public void characters(char ch[], int start, int length)
{
//Don't bother if buffer isn't initialized
if(buf != null)
{
for (int i=start; i<start+length; i++)
{
buf.append(ch[i]);
}
}
}
}
My updated code thus far (still no speed increase):
package com.sltrib.utilities;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class RSSHandler extends DefaultHandler
{
// creats a news item class to hold data within loop
public class NewsItem
{
public String title;
public String subhead;
public String link;
public String byline;
public String description;
public String storytext;
public String cmsstoryid;
public String pubDate;
public String keyword;
public String category;
public String subcategory;
public String slotreference;
public String lastModTime;
public ArrayList<PhotoItem> photos = new ArrayList<PhotoItem>();
#Override
public String toString()
{
return title;
}
}
//creates a photo item class to hold image data within loop
public class PhotoItem
{
public String photoid; //tribs id
public String caption;
public String height;
public String width;
public String photo; //full path to photo
public String thumbnail; //full path to thumbnail
public int articleid;
public String photolastmodified;
#Override
public String toString()
{
return photo;
}
}
//creates instances of classes to be used in loop
private StringBuilder buf; //to hold element characters with loop
private ArrayList<NewsItem> feedItems;
private NewsItem item;
private PhotoItem photoitem;
//initialize variables of whether or not it's within an item (or photo item)
private boolean inItem = false;
private int currentTagId = 0;
//
public ArrayList<NewsItem> getParsedItems() {
return feedItems;
}
#Override
public void startDocument()
{
feedItems = new ArrayList<NewsItem>(); //creates an array to hold feed items
}
//Called at the head of each new element
#Override
public void startElement(String uri, String name, String qName, Attributes atts)
{
//gets the id of the current tag
currentTagId = 0;
String tmpId = atts.getValue("id");
if(tmpId != null)
{
currentTagId = Integer.parseInt(tmpId);
}
//creates a news item
if (currentTagId == 99) // <item>
{
item = new NewsItem();
inItem = true;
}
//creates a photo item
else if (currentTagId == 21) { // <image>
photoitem = new PhotoItem();
}
//creates a string builder if it's a tag within an article or a photo
else if (inItem && currentTagId > 0 && currentTagId < 29)
{
buf = new StringBuilder();
}
}
//Called at the tail of each element end
#Override
public void endElement(String uri, String name, String qName)
{
// it's not getting the tag id - how?
Log.d("XML", "endElement:" + Integer.toString(currentTagId));
if (currentTagId == 99) // </item>
{
Log.d("XML", "Should be adding item: " + item.title);
feedItems.add(item);
inItem=false;
}
else if (currentTagId == 21) // </image>
{
try {
item.photos.add(photoitem);
} catch (Exception e) {
System.out.println(e);
}
}
else
{
switch(currentTagId)
{
case 1: item.title = buf.toString(); break;
case 2: item.subhead = buf.toString(); break;
case 3: item.link = buf.toString(); break;
case 4: item.byline = buf.toString(); break;
case 5: item.description = buf.toString(); break;
case 6: item.storytext = buf.toString(); break;
case 11: item.cmsstoryid = buf.toString(); break;
case 14: item.pubDate = buf.toString(); break;
case 15: item.lastModTime = buf.toString(); break;
case 16: item.keyword = buf.toString(); break;
case 17: item.category = buf.toString(); break;
case 18: item.subcategory = buf.toString(); break;
case 19: item.slotreference = buf.toString(); break;
case 22: photoitem.caption = buf.toString(); break;
case 23: photoitem.photoid = buf.toString(); break;
case 24: photoitem.photolastmodified = buf.toString(); break;
case 25: photoitem.height = buf.toString(); break;
case 26: photoitem.width = buf.toString(); break;
case 27: photoitem.photo = buf.toString(); break;
case 28: photoitem.thumbnail = buf.toString(); break;
default: if(!inItem) buf = null;
}
}
}
//Called with character data inside elements
#Override
public void characters(char ch[], int start, int length)
{
if(buf != null)
{
String chars = new String(ch, start, length); // get all text value inside the element tag
chars = chars.trim(); // remove all white-space characters
buf.append(chars);
}
}
}
Perhaps you are already doing this, but I just wanted to reiterate that this should be done on another thread. The user wont think the app has crashed if you display a progress indicator (spinner) and keep the GUI responsive.
If you are not doing this on a background thread, it could be making this artificially slow because the system is fighting to keep the user interface going.
As to why this is slow, there is a TON of branching. The more if statements you have, and the more elses (etc) you have, the more difficult it is for the branch predictor do do its job.
Also, I can't tell if you are downloading the images here, but if you are, that should be done asynchronously after the text data is retrieved and displayed to the user (to make the user interface more responsive).