Get more information in arraylist - android

I'm developing an Android application for read some information from a XML file on the web. At first, I had a problem to parsing. Now my problem is that my code read only one information. I've created my class MyFilm. How can I insert all information from that file in my arraylist. Thank you in advance.
public class FilmListActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new WebService() {
#Override
protected ArrayList<MyFilm> doInBackground(Object... params) {
ArrayList<MyFilm> arr = new ArrayList<MyFilm>();
Intent intent = getIntent();
String pkg = getPackageName();
try {
MyFilm parametriRicerca = new MyFilm();
parametriRicerca = (MyFilm) intent.getSerializableExtra(pkg+".MyFilm");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
URL input = new URL("http://whatdowedo.altervista.org/griffith_list2.xml");
xpp.setInput(input.openStream(), null);
int eventType = xpp.getEventType();
String currentTag = null;
MyFilm tmp = new MyFilm();
String title = null;
String regista = null;
String attore = null;
String genere = null;
String paese = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
} else if (eventType == XmlPullParser.TEXT) {
if ("title".equals(currentTag)) {
title = xpp.getText().trim();
}
if("director".equals(currentTag)){
regista = xpp.getText().trim();
}
if("country".equals(currentTag)){
paese = xpp.getText().trim();
}
if("genre".equals(currentTag)){
genere = xpp.getText().trim();
}
if("cast".equals(currentTag)){
attore = xpp.getText().trim();
}
if(parametriRicerca.getTitle().equals(title)){
arr.add(parametriRicerca);
}
}
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
}.execute();
}
abstract class WebService extends AsyncTask<Object, MyFilm, ArrayList<MyFilm>> {
public WebService() {
super();
}
#Override
protected void onPreExecute() {
}
#Override
protected abstract ArrayList<MyFilm> doInBackground(Object... params);
#Override
protected void onPostExecute(ArrayList<MyFilm> result) {
super.onPostExecute(result);
FilmsAdapterView adapter = new FilmsAdapterView(FilmListActivity.this,result);
setListAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Related

outlook mail REST API

I'm trying to get access to my outlook inbox mail.
This the code:
Logger logger = LoggerFactory.getLogger(MainActivity.class);
private static final String TAG = "MainActivity";
private static final String outlookBaseUrl = "https://outlook.office.com/api/v2.0";
private AuthenticationContext _authContext;
private DependencyResolver _resolver;
private OutlookClient _client;
private ListView lvMessages;
private String[] scopes = new String[]{"https://outlook.office.com/Mail.Read"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvMessages = (ListView) findViewById(R.id.lvMessages);
Futures.addCallback(logon(), new FutureCallback<Boolean>() {
#Override
public void onSuccess(Boolean result) {
_client = new OutlookClient(outlookBaseUrl, _resolver);
getMessages();
}
#Override
public void onFailure(Throwable t) {
logger.error("authentication failed", t);
}
});
}
public SettableFuture<Boolean> logon() {
final SettableFuture<Boolean> result = SettableFuture.create();
try {
_authContext = new AuthenticationContext(this, getResources().getString(R.string.AADAuthority), true);
} catch (Exception e) {
Log.e(TAG, "Failed to initialize Authentication Context with error: " + e.getMessage());
_authContext = null;
result.setException(e);
}
if (_authContext != null) {
_authContext.acquireToken(
this,
scopes,
null,
getResources().getString(R.string.AADClientId),
getResources().getString(R.string.AADRedirectUrl),
PromptBehavior.Auto,
new AuthenticationCallback<AuthenticationResult>() {
#Override
public void onSuccess(final AuthenticationResult authenticationResult) {
if (authenticationResult != null && authenticationResult.getStatus() == AuthenticationResult.AuthenticationStatus.Succeeded) {
_resolver = new DependencyResolver.Builder(
new OkHttpTransport().setInterceptor(new LoggingInterceptor()), new GsonSerializer(),
new AuthenticationCredentials() {
#Override
public Credentials getCredentials() {
return new OAuthCredentials(authenticationResult.getAccessToken());
}
}).build();
result.set(true);
}
}
#Override
public void onError(Exception e) {
result.setException(e);
}
}
);
}
return result;
}
public void getMessages() {
logger.info("Getting messages...");
Futures.addCallback(_client.getMe().getMessages().top(10).read(), new FutureCallback<List<Message>>() {
#Override
public void onSuccess(final List<Message> result) {
logger.info("Preparing messages for display.");
List<Map<String, String>> listOfMessages = new ArrayList<Map<String, String>>();
for (Message m : result) {
Map<String, String> oneMessage = new HashMap<String, String>();
oneMessage.put("subject", m.getSubject());
if (m.getFrom() != null && m.getFrom().getEmailAddress() != null) {
oneMessage.put("from", "From: " + m.getFrom().getEmailAddress().getAddress());
}
listOfMessages.add(oneMessage);
}
final SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, listOfMessages,
android.R.layout.simple_list_item_2,
new String[]{"subject", "from"},
new int[]{android.R.id.text1, android.R.id.text2});
runOnUiThread(new Runnable() {
#Override
public void run() {
lvMessages.setAdapter(adapter);
}
});
}
#Override
public void onFailure(final Throwable t) {
logger.error(t.getMessage(), t);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
_authContext.onActivityResult(requestCode, resultCode, data);
}
#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);
}
It works.
but when I'm try to login there's an error message shown :
We're unable to complete your request
Microsoft account is experiencing technical problems. Please try again
later.
How can I solve this?

null object in onSaveInstanceState method

i'm trying to save object(saveMOvie) in onSaveinstanceState to restore it on screen rotated when debugging the code using tablet with main and detail fragments are next to each other the value of object (saveMOvie) is null but when using mobile phone with only one fragment on screen the value of object (saveMOvie) doesn't equal null could anyone tell me why ??
MainActivityFragment
public class MainActivityFragment extends Fragment {
Movie moviesStore[];
GridView gridView;
String[] moviesImages;
View rootView;
ImageAdapter imgadpt;
boolean flag;
OnNewsItemSelectedListener onis;
Movie saveMOvie = new Movie();
public interface OnNewsItemSelectedListener {
public void onMovieSelected(Movie movie);
}
public MainActivityFragment() {
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();//3shan myy7slash duplicate
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
onis = (OnNewsItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnNewsItemSelectedListener");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.open_settings_activity) {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
//refresh used when there is no connection
} else if (id == R.id.Refresh_activity) {
onStart();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String mode = prefs.getString(getString(R.string.key),
getString(R.string.default_value));
if (mode.equals("popular") || mode.equals("top_rated")) {
new FetchMovies().execute(mode);
} else {
if (flag) {
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
FavouriteActivityFragment fav = new FavouriteActivityFragment();
fragmentTransaction.replace(R.id.frag_main, fav);
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else {
Intent intent = new Intent(getActivity(), FavouriteActivity.class);
startActivity(intent);
}
}
}
#Override
public void onStart() {
super.onStart();
transaction.commit();
flag = isTablet(getActivity());
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf == null && nf.isConnected() != true) {
Snackbar snackbar = Snackbar
.make(rootView, "Network Not Available", Snackbar.LENGTH_LONG)
.setAction("RECONNECT", new View.OnClickListener() {
#Override
public void onClick(View view) {
onStart();
}
});
snackbar.show();
}
updateMovies();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("movie",saveMOvie);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
onis.onMovieSelected(saveMOvie);
}
setHasOptionsMenu(true);
rootView = inflater.inflate(R.layout.fragment_main, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridView);
return rootView;
}
public class FetchMovies extends AsyncTask<String, Void, Movie[]> {
private final String Log_Tag = FetchMovies.class.getSimpleName();
private Movie[] getMovieDataFromJson(String moviesJasonStr)
throws JSONException
{
final String lists = "results";
final String decription = "overview";
final String originalTitle = "original_title";
final String moviePoster = "poster_path";
final String userRating = "vote_average";
final String releaseDate = "release_date";
final String id = "id";
JSONObject moviesJason = new JSONObject(moviesJasonStr);
JSONArray moviesArray = moviesJason.getJSONArray(lists);
// String[] resultStrs = new String[moviesArray.length()];
moviesStore = new Movie[moviesArray.length()];
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject oneMovieInfo = moviesArray.getJSONObject(i);
moviesStore[i] = new Movie();
moviesStore[i].setPlotSynopsis(oneMovieInfo.getString("overview"));
moviesStore[i].setUserRating(oneMovieInfo.getString("vote_average"));
moviesStore[i].setReleaseDate(oneMovieInfo.getString("release_date"));
moviesStore[i].setOriginalTitle(oneMovieInfo.getString("original_title"));
moviesStore[i].setMoviePoster(oneMovieInfo.getString("poster_path"));
moviesStore[i].setId(oneMovieInfo.getString("id"));
}
return moviesStore;
}
#Override
protected Movie[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviesJasonStr = null;
StringBuilder baseUrl = new StringBuilder("https://api.themoviedb.org/3/movie/");
baseUrl.append(params[0]);
baseUrl.append("?api_key=");
baseUrl.append(BuildConfig.MOVIE_DP_API_KEY);
try {
// URL url = new URL("https://api.themoviedb.org/3/movie/popular?api_key=d51b32efc0520227b7c1c67e0f6417f6");
URL url = new URL(baseUrl.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
moviesJasonStr = buffer.toString();
Log.v(Log_Tag, "movies Jason String :" + moviesJasonStr);
} catch (IOException e) {
Log.e(Log_Tag, "Error ", e);
// Toast.makeText(getActivity(),"there is no internet connection",Toast.LENGTH_LONG).show();
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(Log_Tag, "Error closing stream", e);
}
}
}
try {
return getMovieDataFromJson(moviesJasonStr);
} catch (JSONException e) {
Log.e(Log_Tag, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Movie[] result) {
if (result != null) {
moviesImages = new String[result.length];
for (int i = 0; i < result.length; i++) {
StringBuilder baseUrl = new StringBuilder();
baseUrl.append("http://image.tmdb.org/t/p/w185/");
baseUrl.append(result[i].getMoviePoster());
moviesImages[i] = baseUrl.toString();
}
imgadpt = new ImageAdapter(getActivity(), moviesImages);
gridView.setAdapter(imgadpt);
// if(flag){
// onis.onMovieSelected(moviesStore[0]);}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String posterUrl = (String) imgadpt.getItem(position);
saveMOvie = moviesStore[position];
if (flag) {
onis.onMovieSelected(moviesStore[position]);
} else {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("movie", moviesStore[position]);
startActivity(intent);
}
}
});
} else {
Toast.makeText(getActivity(), "Cannot Fetch Data from api check your internet Connection", Toast.LENGTH_LONG).show();
}
}
}
}
When onCreate(savedInstanceState) is called, check whether savedInstanceState is null, and if not, then getExtras from it (as it's a Bundle).
if (savedInstanceState != null)
savedInstanceState.getParcelable(key)
Then do whatever you'd like with the object.

Show Parse Object data in a TextView

obj is a string with the Id for a specific object in my parse database. I want to get individual rows values and show them in a text view. The below code is what I've got. Not sure why but the query alwasy seems tho return empty. Thus my strings restName,restCuisine,etc all have their initialized values only i.e their values aren't changing because of my query. Any help would be appreciated
public class SingleRestraunt extends ActionBarActivity {
private GoogleMap map;
TextView resteName, resteCuisine, resteLocation, resteAddress;
String restName = "nothing", obj, restCuisine = "nothing",
restLocation = "nothing", restAddress = "nothing";
Double Lang = 19.144378, Long = 72.837135;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_restraunt);
resteName = (TextView) findViewById(R.id.restrauntName);
resteCuisine = (TextView) findViewById(R.id.restrauntCuisine);
resteLocation = (TextView) findViewById(R.id.restrauntLocation);
resteAddress = (TextView) findViewById(R.id.restrauntAddress);
Intent i = getIntent();
obj = i.getStringExtra("restId");
getDetails(obj);
}
private void getDetails(final String obj) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("resdb");
query.getInBackground(obj, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
restName = object.getString("name");
restCuisine = object.getString("cuisine");
restLocation = object.getString("location");
restAddress = object.getString("address");
} else {
e.printStackTrace();
}
}
});
prepareMap(Lang, Long);
addData();
}
public void addData() {
resteName.setText(restName);
resteCuisine.setText(restCuisine);
resteLocation.setText(restLocation);
resteAddress.setText(restAddress);
}
public void prepareMap(Double Lang, Double Long) {
final LatLng REST = new LatLng(Lang, Long);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
#SuppressWarnings("unused")
Marker hamburg = map.addMarker(new MarkerOptions().position(REST)
.title("Here"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(REST, 15));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.single_restraunt, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
I think it is not correct to call prepareMap(Lang, Long) and addData() after to the call query.getInBackground(...) because "In background" means in a different Thread. You should reorder your calls like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("resdb");
query.getInBackground(obj, new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
restName = object.getString("name");
restCuisine = object.getString("cuisine");
restLocation = object.getString("location");
restAddress = object.getString("address");
// Update your info after to get the rest info
prepareMap(Lang, Long);
addData();
} else {
e.printStackTrace();
}
}
});
I hope this help you!

ListView displaying incorrect title

I have a simple application that pulls an XML file from pc worlds RSS feed here:
http://feeds.pcworld.com/pcworld/latestnews
I want to display the name of the titles in a ListView then when the user selects one the article opens up in a browser window.
The application is working the only thing is that the title is not being displayed correctly in the ListView.
It should be something like this:
Make you website stand out with Windows 8
But instead it is this:
com.example.simplerss.Item#424b9998
Any ideas?
This is my code for the MainActivity
public class MainActivity extends ListActivity {
ArrayAdapter<Item> adapter;
List<Item>items;//Holds item objects containing info relating to element pulled from XML file.
Item item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize variables
items = new ArrayList<Item>();
new PostTask().execute();
adapter= new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_1, items);
setListAdapter(adapter);
}
private InputStream getInputStream(URL url) {
try{
return url.openConnection().getInputStream();
}catch(IOException e){
return null;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Uri uri = items.get(position).getLink();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//ASYNC CLASS
private class PostTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... arg0) {
try{
//link to data source
URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews");
//Set up parser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
//get XML from input stream
InputStream in = getInputStream(url);
if (in == null) {
throw new Exception("Empty inputstream");
}
xpp.setInput(in, "UTF_8");
//Keep track of which tag inside of XML
boolean insideItem = false;
//Loop through the XML file and extract data required
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
Log.v("ENTER", String.valueOf(xpp.getEventType()));
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
//Create new item object
item = new Item();
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem){
item.setTitle(xpp.nextText());
Log.i("title", item.getTitle());
}
}
else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem){
item.setDescription(xpp.nextText());
}
}
else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem){
item.setLink(Uri.parse(xpp.nextText()));
}
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
//add item to list
items.add(item);
}
eventType = xpp.next(); //move to next element
publishProgress();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return "COMPLETED";
}
#Override
protected void onProgressUpdate(Integer... values) {
adapter.notifyDataSetChanged();
}
public void onPostExecute(String s) {
Toast.makeText(getApplicationContext(), s + " Items: " + items.size(), Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
}
}
and for the Item Class
public class Item {
//Variables
private String title;
private Uri link;
private String description;
public Item() {
super();
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Uri getLink() {
return link;
}
public void setLink(Uri link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Override the toString() method in Item.
#Override
public String toString() {
return title;
}
This should solve your problem.
Right now, the ArrayAdapter sets its View's texts to Item.toString(), but this is the default method of Object that returns the Object's ID. With overriding it, you give it a meaningful value, in your case the title.
I think the problem lies in:
else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem){
item.setTitle(xpp.nextText());
Log.i("title", item.getTitle());
}
}
Here, getName() is a method from the Java Class object. The method you want is readContent() I think. I haven't used this library so that may not be exactly correct but you can certainly find what you need in the docs.

How to parse local xml file to get country details android?

i have to parse xml file to get country details like country name and country postal code.
how can i parse country names to spinner adapter and when i select perticular country using spinner i have to display particular country code in textview.
please help me.
Thanks in advance.
Here is a code to parse Xml file where you will have to pass inputstream of your local xml file.
public static ArrayList<Country> parseCountry(Context context, InputStream inputStream) {
String KEY = "";
String VALUE = null;
ArrayList<Country> arrCountires = new ArrayList<Country>();
Country country = null;
ArrayList<State> arrStates = null;
State state= null;
ArrayList<City> arrCities = null;
City city = null;
try {
InputStreamReader inputreader = null;
if(inputStream != null) {
inputreader = new InputStreamReader(inputStream);
}
if(inputreader != null) {
XmlPullParserFactory factory = null;
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = null;
xpp = factory.newPullParser();
xpp.setInput(inputreader);
int eventType = 0;
eventType = xpp.getEventType();
eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_TAG) {
KEY = xpp.getName();
if(KEY.equalsIgnoreCase(TAGS.COUNTRIES)) {
arrCountires = new ArrayList<Country>();
}else if(KEY.equalsIgnoreCase(TAGS.COUNTRY)) {
country = new Country();
arrStates = new ArrayList<State>();
country.setCountryId(xpp.getAttributeValue(null, TAGS.ID));
}else if(KEY.equalsIgnoreCase(TAGS.STATE)) {
state = new State();
arrCities = new ArrayList<City>();
state.setStateId(xpp.getAttributeValue(null, TAGS.ID));
}else if(KEY.equalsIgnoreCase(TAGS.CITY)) {
city = new City();
city.setCityId(xpp.getAttributeValue(null, TAGS.ID));
}
}else if(eventType == XmlPullParser.END_TAG) {
KEY = xpp.getName();
if(KEY.equalsIgnoreCase(TAGS.COUNTRY)) {
country.setArrStates(arrStates);
arrCountires.add(country);
}else if(KEY.equalsIgnoreCase(TAGS.COUNTRY_NAME)) {
country.setCountryName(VALUE);
}else if(KEY.equalsIgnoreCase(TAGS.STATE_NAME)) {
state.setStateName(VALUE);
}else if(KEY.equalsIgnoreCase(TAGS.STATE)) {
state.setArrCities(arrCities);
arrStates.add(state);
}else if(KEY.equalsIgnoreCase(TAGS.CITY)) {
arrCities.add(city);
}else if(KEY.equalsIgnoreCase(TAGS.CITY_NAME)) {
city.setCityName(VALUE);
}
}else if(eventType == XmlPullParser.TEXT) {
VALUE = xpp.getText();
}
eventType = xpp.next();
}
}
}
catch (Exception e) {
e.printStackTrace();
}finally {
if(inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return arrCountires;
}
Here is a Country class with Getter and Setter methods.
public class Country {
String countryId;
String countryName;
ArrayList<State> arrStates;
public ArrayList<State> getArrStates() {
return arrStates;
}
public void setArrStates(ArrayList<State> arrStates) {
this.arrStates = arrStates;
}
public String getCountryId() {
return countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
Here is a Adapter class to set country in the spinner.
private class CountryAdapter implements SpinnerAdapter{
ArrayList<Country> data;
public CountryAdapter(ArrayList<Country> data){
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return android.R.layout.simple_spinner_dropdown_item;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView v = new TextView(getApplicationContext());
v.setTextColor(Color.BLACK);
v.setText(data.get(position).getName());
v.setTextSize(15);
v.setPadding(10, 10, 10, 10);
v.setSingleLine();
v.setEllipsize(TruncateAt.END);
return v;
}
#Override
public int getViewTypeCount() {
return android.R.layout.simple_spinner_item;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isEmpty() {
return false;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return this.getView(position, convertView, parent);
}
}
Here is a Interface by which you can get the selected country from the spinner
OnItemSelectedListener OnCountrySelected = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View v, int position,
long id) {
if(position != AdapterView.INVALID_POSITION) {
System.out.println("Country name = " + arrCountries.get(position).getName());
//Here you can set this value to the textview
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
};
Here is a way how you can set the Listener to the spinner
spCountry.setOnItemSelectedListener(OnCountrySelected);
Here is a code to open file as inputstream from assets
try {
InputStream inputStream = v.getContext().getAssets().open("path of file");
ArrayList<Country> arrCountries = parseCountry(this, inputStream);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
When you get the response in the array of Country then set adapter to the spinner
CountryAdapter countryAdapter = new CountryAdapter(arrCountry);
spCountry.setAdapter(countryAdapter);

Categories

Resources