I have a listView populated with JSON data obtained from YouTube:
private VideosListView listView;
As of now - the listView succesfully populates with the data I'm looking for however I need to be able to repopulate it with updated data. Currently - I execute/populate the initial listView using:
new GetYouTubeUserVideosTask(responseHandler, playlist).execute();
What I'd like to do is repopulate it using a different value for String playlist:
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
View vg = findViewById(R.layout.home);
vg.invalidate();
P.S.
What I've attempted to use thus far does not seem to be working - nothing happens when I swipe the ViewPager - however if I set a toast there it will appear when swiping it.
I don't know why this has been such a difficult issue to nail down - but I'd be more than happy to leave a tip via paypal for anyone who can solve this issue.
http://i.stack.imgur.com/e0QqU.png
JAVA: Home.java
public class Home extends YouTubeBaseActivity implements
VideoClickListener {
private VideosListView listView;
private int mCurrentTabPosition = NO_CURRENT_POSITION;
private static final int NO_CURRENT_POSITION = -1;
private ListView drawerListView;
String playlist = "knocksteadyTV";
Activity activity;
int imageArray[];
String[] stringArray;
String runPrevious = "No";
private OnPageChangeListener mPageChangeListener;
ImagePagerAdapter adapter = new ImagePagerAdapter();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ViewPager mPager = (ViewPager) findViewById(R.id.view_pager);
adapter.notifyDataSetChanged();
mPager.setAdapter(adapter);
mPager.setOnPageChangeListener(mPageChangeListener);
listView = (VideosListView) findViewById(R.id.videosListView);
listView.setOnVideoClickListener(this);
new GetYouTubeUserVideosTask(responseHandler, playlist).execute();
mPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int pos) {
Toast.makeText(getApplicationContext(), "onPageSelected",
Toast.LENGTH_SHORT).show();
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist).execute();
adapter.notifyDataSetChanged();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "onPageScrolled",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(int pos) {
Toast.makeText(getApplicationContext(),
"onPageScrollStateChanged", Toast.LENGTH_SHORT).show();
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
adapter.notifyDataSetChanged();
}
});
mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
position = mCurrentTabPosition;
int oldPos = mPager.getCurrentItem();
if (position > oldPos) {
System.out.print(position);
// Moving to the right
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
View vg = findViewById(R.layout.home);
vg.invalidate();
} else if (position < oldPos) {
// Moving to the Left
System.out.print(position);
String playlist = "TheMozARTGROUP";
new GetYouTubeUserVideosTask(responseHandler, playlist)
.execute();
View vg = findViewById(R.layout.home);
vg.invalidate();
}
mPager.setOnPageChangeListener(mPageChangeListener);
}
private void onTabChanged(PagerAdapter adapter,
int mCurrentTabPosition, int position) {
// TODO Auto-generated method stub
}
};}
private class MyActivityGetYouTubeUserVideosTask extends GetYouTubeUserVideosTask {
public MyActivityGetYouTubeUserVideosTask(Handler replyTo,
String username) {
super(replyTo, username);
// TODO Auto-generated constructor stub
}
#Override
protected void onPostExecute(Void result) {
if (result != null) {
// TODO update your list data
// note: assuming your data is stored in an ArrayList<MyData>,
// you cannot create a new one. you must clear() the current
// ArrayList and add() the result to it.
}
adapter.notifyDataSetChanged();
}
}
private void _initMenu() {
}
Handler replyTo = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(this, Player.class);
intent.putExtra("id", video.getId());
intent.putExtra("title", video.getTitle());
intent.putExtra("uploader", video.getUploader());
intent.putExtra("viewCount", video.getviewCount());
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter(Activity act, int[] mImages,
String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn,
R.drawable.island_up_btn, R.drawable.latin_up_btn,
R.drawable.pop_up_btn, R.drawable.samba_up_btn };
private String[] stringArray = new String[] { "vevo",
"TheMozARTGROUP", "TimMcGrawVEVO", "TiestoVEVO",
"EminemVEVO" };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Home.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
drawerListView.setItemChecked(position, true);
setTitle("......");
String text = "menu click... should be implemented";
Toast.makeText(Home.this, text, Toast.LENGTH_LONG).show();
drawerLayout.closeDrawer(drawerListView);
}
}
}
}
JAVA: GetYoutubeVideosTask.java
public class GetYouTubeUserVideosTask extends AsyncTask<Void, Void, Void> {
public static final String LIBRARY = "Library";
private final Handler replyTo;
private final String username;
public GetYouTubeUserVideosTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
/*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
List<Video> videos = new ArrayList<Video>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
String id = jsonObject.getString("id");
String viewCount = jsonObject.getString("viewCount");
String uploader = jsonObject.getString("uploader");
String url;
try {
url = jsonObject.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = jsonObject.getJSONObject("player").getString("default");
}
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("hqDefault");
videos.add(new Video(title, id, viewCount, uploader, url, thumbUrl));
}
Library lib = new Library(username, videos);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
return null;
}
/*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
//adapter.notifyDataSetChanged();
}
}
Related
Im new on java and im doing a app for finish my university. This app have a SearchView filtering on a ListView getting data from a JSON. Im almost finishing that but im stuck after the filter part.
After input on the SearchBar and filter returns the result I cant open a new intent getting the ID from the JSON. I only can open the intent using the position ListView number (that doesn't work for my necessity because of filter process).
The image below shows exactly the issue:
Image
So my necessity is: Open a intent using the ID stored on the JSON for avoid the issue of changing position ID after filter result.
I dont have any idea how I fix this.
Bean:
public class Model {
private String description;
private int id;
public Model(int id, String description) {
this.setId(id);
this.setDescription(description);
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
Main:
public class MainActivity extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private ListView list;
private ListViewAdapter adapter;
private SearchView editsearch;
public static ArrayList<Model> modelArrayList = new ArrayList<Model>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listview);
loadDataJSON();
adapter = new ListViewAdapter(this);
list.setAdapter(adapter);
editsearch = (SearchView) findViewById(R.id.search);
editsearch.setOnQueryTextListener(this);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int a = position;
Intent myIntent = new Intent(MainActivity.this, Info.class);
myIntent.putExtra("valor", a);
startActivity(myIntent);
}
});
}
public String loadJSON(String arq) {
String json = null;
try {
InputStream is = getAssets().open(arq);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void loadDataJSON() {
String arquivo = loadJSON("lista.json");
try {
JSONObject obj = new JSONObject(arquivo);
JSONArray a = obj.getJSONArray("locais");
for (int i = 0; i < a.length(); i++) {
JSONObject item = a.getJSONObject(i);
Model model = new Model(item.getInt("id"),item.getString("description"));
modelArrayList.add(model);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String text = newText;
adapter.filter(text);
return false;
}
#Override
public boolean onClose() {
// TODO Auto-generated method stub
return false;
}
Adapter:
public class ListViewAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
public ArrayList<Model> arraylist;
public ListViewAdapter(Context context ) {
mContext = context;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Model>();
this.arraylist.addAll(MainActivity.modelArrayList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return MainActivity.modelArrayList.size();
}
#Override
public Model getItem(int position) {
return MainActivity.modelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.name.setText(MainActivity.modelArrayList.get(position).getDescription());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
MainActivity.modelArrayList.clear();
if (charText.length() == 0) {
MainActivity.modelArrayList.addAll(arraylist);
} else {
for (Model mp : arraylist) {
if (mp.getDescription().toLowerCase(Locale.getDefault()).contains(charText)) {
MainActivity.modelArrayList.add(mp);
}
}
}
notifyDataSetChanged();
}
Info:
public class Info extends Activity {
TextView aaa, bbb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
aaa = (TextView) findViewById(R.id.aaa);
bbb = (TextView) findViewById(R.id.bbb);
Intent mIntent = getIntent();
int id = mIntent.getIntExtra("valor",0);
String arquivo = loadJSON("lista.json");
try {
JSONObject obj = new JSONObject(arquivo);
JSONArray a = obj.getJSONArray("locais");
JSONObject item = a.getJSONObject(id);
aaa.setText(item.getString("id"));
bbb.setText("Base: "+item.getString("description"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public String loadJSON(String arq) {
String json = null;
try {
InputStream is = getAssets().open(arq);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
JSON:
{ "locais": [{
"id": "1",
"description": "Text A"
}, {
"id": "2",
"description": "Text B"
}]}
use int a = modelArrayList.get(position).getId() instead. So you will get id from JSON
You need to use that intent in ListViewAdapter
Hope its works fine
I want to check the roll and roll check days if they are equal then auto check that check box and can also unchecked that if needed by user.
1.)Check if roll and rollcheck data from Json are equal then check the checkbox automatically.
2.)user can also uncheck that automatically checked checkbox
MainActivity.java
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
FloatingActionButton fab;
ListView list;
TextView txt_menu;
String dipilih;
private static final String TAG = MainActivity.class.getSimpleName();
Adapter adapter;
ProgressDialog pDialog;
List<Data> itemList = new ArrayList<Data>();
private static String url = "http://url.php";
public static final String TAG_NAMA = "nama";
public static final String TAG_ROLL = "roll";
public static final String TAG_ROLLCheck = "rollcheck";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
list = (ListView) findViewById(R.id.list_menu);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "No check box selected";
}
formSubmit(dipilih);
}
});
callVolley();
adapter = new Adapter(this, (ArrayList<Data>) itemList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long l) {
adapter.setCheckBox(position);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("title");
dialog.setCancelable(true);
txt_menu = (TextView) dialogView.findViewById(R.id.txt_menu);
txt_menu.setText(hasil);
dialog.setNeutralButton("CLOSE", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void callVolley(){
itemList.clear();
// menapilkan dialog loading
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
showDialog();
// membuat request JSON
JsonArrayRequest jArr = new JsonArrayRequest(url, new
Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NAMA));
item.setRoll(obj.getString(TAG_ROLL));
item.setRollCheck(obj.getString(TAG_ROLLCheck));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
// menambah request ke request queue
AppController.getInstance().addToRequestQueue(jArr);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Adapter.java
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
viewHolder.roll = (TextView) vi.findViewById(R.id.roll);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
viewHolder.menu.setText(items.getMenu());
viewHolder.roll.setText(items.getRoll());
}
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView roll;
TextView menu;
CheckBox checkBox;
}
}
Data.java
public class Data {
private String roll;
private String menu;
private boolean check;
private String roll_check;
public Data() {}
public Data(String roll,String menu, boolean check,String roll_check) {
this.roll=roll;
this.menu = menu;
this.check = check;
this.roll_check = roll_check;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getRollCheck() {
return roll_check;
}
public void setRollCheck(String roll_check) {
this.roll_check = roll_check;
}
public String getMenu() {
return menu;
}
public void setMenu(String menu) {
this.menu = menu;
}
public boolean isCheckbox() {
return check;
}
public void setCheckbox(boolean check) {
this.check = check;
}
}
I have a spinner that i select data from which goes into a arraylist that is used with a list view to display the contents. I know the values are going into the Arraylist but when it comes to the list view it does not work correctly.
What happens is the first item will load in fine, but when i add another item the previous one disappears, while the new one is displayed one position down from the previous one, this repeats for each one i added.
create itinerary code:
public class CreateItinerary extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
TextView txtDate;
private Spinner spinnerAttraction;
private Spinner spinnerTransport;
private boolean saved;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
private ProgressDialog pDialog;
private List<String> lables = new ArrayList<String>();
private ArrayList<ItineraryAdapter>Entities;
private ArrayList<ItineraryAdapter>finalEntities;
private LayoutInflater myInflator;
private View myView;
private DBManager db;
private myAdapter adapter;
private int ID;
private String NAME;
private String LOCATION;
private String TIME;
static final int DIALOG_ID = 0;
int hour_x;
int min_x;
private ListView ls;
private TextView TextTime;
private String ItineraryName;
private String URL_ATTRACTIONS = "http://10.0.2.2/TravelApp/get_all_spinner.php";
private String URL_TRANSPORT = "http://10.0.2.2/TravelApp/get_all_transport_minor.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_itinerary);
txtDate = (TextView) findViewById(R.id.tvSelectDate);
saved = false;
ls = (ListView)findViewById(R.id.listCreateItinerary);
myInflator = getLayoutInflater();
myView = myInflator.inflate(R.layout.list_create_itinerary, null);
spinnerAttraction = (Spinner) findViewById(R.id.spinnerAttraction);
spinnerTransport = (Spinner) findViewById(R.id.spinnerTransport);
db = new DBManager(this);
categoriesList = new ArrayList<Category>();
Entities = new ArrayList<ItineraryAdapter>();
finalEntities = new ArrayList<ItineraryAdapter>();
// spinner item select listener
spinnerAttraction.setOnItemSelectedListener(this);
spinnerTransport.setOnItemSelectedListener(this);
new GetAttractions().execute();
showTimePickerDialog();
Bundle bundle = getIntent().getExtras();
ItineraryName = bundle.getString("Itinerary Name");
(this).registerForContextMenu(ls);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(v.getId()== R.id.listCreateItinerary){
this.getMenuInflater().inflate(R.menu.context_menu,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.menuDelete:
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_button, 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 (saved == false) {
if (id == R.id.go_home) {
final TextView alertMessage = new TextView(this);
alertMessage.setText(" All changes will be lost are you sure you want to return back to the home page? ");
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Unsaved changes")
.setView(alertMessage)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
})
.setNegativeButton("No", null)
.create();
dialog.show();
}
}
else if(saved == true){
if (id == R.id.go_home) {
Intent i = new Intent(getApplicationContext(), QavelNav.class);
startActivity(i);
}
}
return super.onOptionsItemSelected(item);
}
public void pickDate(View v) {
DatePickerClass datepicker = new DatePickerClass();
datepicker.setText(v);
datepicker.show(getSupportFragmentManager(), "datepicker");
System.out.println(getDate());
}
public String getDate() {
String date;
date = txtDate.getText().toString();
return date;
}
public void addAttractionToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void addTransportToItinerary(View v){
Entities.add(new ItineraryAdapter(ID,NAME,LOCATION,null));
loadAttractions();
System.out.println(ItineraryName);
}
public void loadAttractions(){
adapter = new myAdapter(Entities);
ListView ls = (ListView) findViewById(R.id.listCreateItinerary);
ls.setAdapter(adapter);
for(int i =0; i < finalEntities.size(); i++){
System.out.println(finalEntities.get(i).NAME + " " + finalEntities.get(i).LOCATION + " " + finalEntities.get(i).TIME);
}
}
public void onSave(View v){
ContentValues values = new ContentValues();
for(int i = 0; i <finalEntities.size();i++) {
values.put(DBManager.ColItineraryName,ItineraryName);
values.put(DBManager.ColDate,txtDate.getText().toString());
values.put(DBManager.ColName,finalEntities.get(i).NAME );
values.put(DBManager.ColLocation,finalEntities.get(i).LOCATION);
values.put(DBManager.ColTime,finalEntities.get(i).TIME);
long id = db.Insert("Itinerary",values);
if (id > 0)
Toast.makeText(getApplicationContext(),"Added to Itinerary", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}
saved = true;
}
public void showTimePickerDialog(){
TextTime = (TextView) myView.findViewById(R.id.tvCreateItineraryTime);
TextTime.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if(id== DIALOG_ID)
return new TimePickerDialog(CreateItinerary.this,KTimePickerListner, hour_x, min_x,false);
return null;
}
protected TimePickerDialog.OnTimeSetListener KTimePickerListner = new TimePickerDialog.OnTimeSetListener(){
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
hour_x = hourOfDay;
min_x = minute;
Toast.makeText(CreateItinerary.this,hour_x+" : " + min_x, Toast.LENGTH_LONG).show();
setTime(hour_x, min_x);
TIME = hour_x + ":" + min_x;
finalEntities.add(new ItineraryAdapter(ID,NAME,LOCATION,TIME));
}
};
public void setTime(int hour, int min){
TextTime.setText(hour_x+":"+min_x);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
NAME = categoriesList.get(position).getName();
LOCATION = categoriesList.get(position).getLocation();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
* */
private void populateSpinner() {
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName() + " - " + categoriesList.get(i).getLocation());
System.out.println(categoriesList.get(i));
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerAttraction.setAdapter(spinnerAdapter);
spinnerTransport.setAdapter(spinnerAdapter);
}
/**
* Async task to get all attraction categories
* */
private class GetAttractions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching attraction categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_ATTRACTIONS, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("attraction");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
// new GetTransport().execute();
}
}
private class GetTransport extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CreateItinerary.this);
pDialog.setMessage("Fetching transport categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_TRANSPORT, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("transport");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("Id"),
catObj.getString("Name"), catObj.getString("Location"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
class myAdapter extends BaseAdapter {
public ArrayList<ItineraryAdapter> listItem;
ItineraryAdapter ac;
public myAdapter(ArrayList<ItineraryAdapter> listItem) {
this.listItem = listItem;
}
#Override
public int getCount() {
return listItem.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
ac = listItem.get(position);
TextView Name = (TextView) myView.findViewById(R.id.tvCreateItineraryName);
Name.setText(ac.NAME);
TextView Location = (TextView) myView.findViewById(R.id.tvCreateItineraryLocation);
Location.setText(ac.LOCATION);
return myView;
}
public void deleteItineraryItem(){
Entities.remove(ID);
finalEntities.remove(ID);
loadAttractions();
}
}
}
The public void loadAttractions(){..., is the medthod code that updates the list view, the 2 methods above it relate to separate buttons and add the spinner item to the array list (Entities), thank you to anyone who can help me.
instead of:
#Override
public Object getItem(int position) {
return null;
}
try this code:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listItem.get(position); //return list item
}
I am trying to make a activity which has a listview ,it has edittexts,it displays the previously stored data and when clicked on edittexts and edit them, it stores the edited data and displays new data on list view. I am using hashmap to parse json values. Could you help me?
Here is my code:
public class AdditionalNutrientGoalsActivity extends ActionBarActivity
{
private static final String TAG = AdditionalNutrientGoalsActivity.class.getName();
HashMap<String, Integer> map = new HashMap<String, Integer>();
private String[] arrText =
new String[]{"Saturated Fat","Trans fat","polyunsaturated fat","Sodium","Fiber","Monosaturated Fat","Potassium"
,"Sugar","Iron","Cholestrol","Calcium","Vitamin C","Vitamin A"};
private String[] arrTemp =
new String[]{ "00 %","00 %","00 %","38 %","77 %","1049 %","00 %","00 %","38 %"
,"77 %","1049 %","77 %","1049 %"};// for now hardcodedvalues
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_additional_nutrient_goals);
MyListAdapter myListAdapter = new MyListAdapter();
ListView listView = (ListView) findViewById(R.id.customlist1);
listView.setAdapter(myListAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("list view", position + "");
showDialog(arrText[position]);
// Toast.makeText(getApplicationContext(),"Saved",Toast.LENGTH_SHORT).show();
}
});
ImageView IVback = (ImageView) findViewById(R.id.back);
IVback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AdditionalNutrientGoalsActivity.this.finish();
}
});
GetData getData=new GetData();
getData.execute();
}
void showDialog(String title)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AdditionalNutrientGoalsActivity.this);
// set title
alertDialogBuilder.setTitle(title);
alertDialogBuilder
.setMessage("Enter in gm/day")
.setCancelable(false)
.setPositiveButton("Set", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
//AdditionalNutrientGoalsActivity.this.finish();
}
})
.setView(new EditText(AdditionalNutrientGoalsActivity.this))
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
private class MyListAdapter extends BaseAdapter
{
#Override
public int getCount() {
if(arrText != null && arrText.length != 0){
return arrText.length;
}
return 0;
}
#Override
public Object getItem(int position) {
return arrText[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String data="";
//ViewHolder holder = null;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = AdditionalNutrientGoalsActivity.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.custom_additional_nutri, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.textView45);
holder.editText1 = (TextView) convertView.findViewById(R.id.textView46);
data =holder.editText1.getText().toString();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
holder.textView1.setText(arrText[position]);
holder.editText1.setText(data);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
// arrTemp[holder.ref] = arg0.toString();
saveData saveData=new saveData();
saveData.execute();
}
});
return convertView;
}
private class ViewHolder {
TextView textView1;
TextView editText1;
int ref;
}
}
and this is my GetData functionality:
private class GetData extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("username", SharedPref.getData(getApplicationContext(), SharConstants.username)));
parameters.add(new BasicNameValuePair("password", SharedPref.getData(getApplicationContext(), SharConstants.password)));
// parameters.add(new BasicNameValuePair("token", SharedPref.getData(getApplicationContext(), SharConstants.token)));
parameters.add(new BasicNameValuePair("date_time", SharedPref.getData(getApplicationContext(), SharConstants.date_time)));
GetJsonFromServer getJsonFromServer = new GetJsonFromServer();
String response = getJsonFromServer.getJson(ApiList.getAdditionalNutrientGoals, "POST", parameters);
Log.e(TAG, response);
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try
{
JSONObject jsonObject = new JSONObject(s);
JSONObject response = jsonObject.getJSONObject("response");
if(response.getInt("success") == 1)
{
JSONObject object= response.getJSONObject("data");
ArrayList<HashMap<String,Integer>> parameters = new ArrayList<HashMap<String, Integer>>();
// adding each child node to HashMap key => value
map.put("id",object.getInt("id"));
map.put("user_id",object.getInt("user_id"));
map.put("saturated_fat",object.getInt("saturated_fat"));
map.put("polyunsaturated_fat",object.getInt("polyunsaturated_fat"));
map.put("monounsaturated_fat",object.getInt("monounsaturated_fat"));
map.put("trans_fat",object.getInt("trans_fat"));
map.put("cholesterol",object.getInt("cholesterol"));
map.put("sodium",object.getInt("sodium"));
map.put("potassium",object.getInt("potassium"));
map.put("fiber", object.getInt("fiber"));
map.put("sugar", object.getInt("sugar"));
map.put("Vitamin_A", object.getInt("Vitamin_A"));
map.put("Vitamin_C", object.getInt("Vitamin_C"));
map.put("calcium", object.getInt("calcium"));
map.put("iron", object.getInt("iron"));
parameters.add(map);
Log.d("map","map"+" "+parameters);
}
else
{
Toast.makeText(getApplicationContext(), "Server Error, Try Again Later.", Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e(TAG, e.toString());
Toast.makeText(getApplicationContext(), "Server Error", Toast.LENGTH_LONG).show();
}
}
I am not getting idea as to how to store data and fetch data.
I'm getting two errors in eclipse:
GetXMLTask cannot be resolved to a type line 119:
which is
GetXMLTask task = new GetXMLTask(this);
as well as
mPager cannot be resolved line 151: onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
I believe I've declared and called both GetXMLTask and mPager correctly so I'm not sure exactly what might be causing this.
Any suggestions are greatly appreciated.
Java Source:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.parser_main);
final ActionBar actionBar = getActionBar();
final ViewPager mPager = (ViewPager) findViewById(R.id.view_pager);
adapter.notifyDataSetChanged();
mPager.setAdapter(adapter);
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
mPager.setOnPageChangeListener(mPageChangeListener);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
_initMenu();
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
findViewsById();
listView.setOnItemClickListener(this);
GetXMLTask task = new GetXMLTask(this);
task.execute(new String[] { URL });
}
private void findViewsById() {
listView = (ListView) findViewById(R.id.videosListView);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onClick(View view) {
class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT)
.show();
drawerLayout.closeDrawer(drawerListView);
}
}
mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
position = mCurrentTabPosition;
int oldPos = mPager.getCurrentItem();
Log.d("PK", "Page selected");
if (position > oldPos) {
System.out.print(position);
// Moving to the right
String playlist = "TheMozARTGROUP";
View vg = findViewById(R.layout.home);
vg.invalidate();
}
if (position > oldPos) {
System.out.print(position);
// Moving to the right
String playlist = "TheMozARTGROUP";
View vg = findViewById(R.layout.home);
vg.invalidate();
} else if (position < oldPos) {
// Moving to the Left
System.out.print(position);
String playlist = "TheMozARTGROUP";
View vg = findViewById(R.layout.home);
vg.invalidate();
}
mPager.setOnPageChangeListener(mPageChangeListener);
}
private void onTabChanged(PagerAdapter adapter,
int mCurrentTabPosition, int position) {
Log.d("PK", "Tab changed");
// TODO Auto-generated method stub
}
};
}
private void _initMenu() {
// TODO Auto-generated method stub
class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view,
int position, long id) {
Log.d("pk", "onItemClick");
// Highlight the selected item, update the title, and close the
// drawer
// update selected item and title, then close the drawer
drawerListView.setItemChecked(position, true);
setTitle("......");
Toast.makeText(getApplicationContext(), "Item Clicked",
Toast.LENGTH_SHORT).show();
// Toast.makeText(Home.this, text, Toast.LENGTH_LONG).show();
drawerLayout.closeDrawer(drawerListView);
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter implements
ViewPager.OnPageChangeListener {
public ImagePagerAdapter(Activity act, int[] mImages,
String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn,
R.drawable.island_up_btn, R.drawable.latin_up_btn,
R.drawable.pop_up_btn, R.drawable.samba_up_btn };
private String[] stringArray = new String[] { "vevo",
"TheMozARTGROUP", "TimMcGrawVEVO", "TiestoVEVO",
"EminemVEVO" };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = SAXParserAsyncTaskActivity.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
#Override
public void onPageScrollStateChanged(int pos) {
Log.d("PK", "onPageScrollStateChanged");
// Toast.makeText(getApplicationContext(),
// "onPageScrollStateChanged", Toast.LENGTH_SHORT).show();
// String playlist = "TheMozARTGROUP";
// new GetYouTubeUserVideosTask(responseHandler,
// playlist).execute();
// adapter.notifyDataSetChanged();
//
;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.d("PK", "onPageScrolled");
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "onPageScrolled",
// Toast.LENGTH_SHORT).show();
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
Log.d("pk", "onPageSelected");
}
// private inner class extending AsyncTask
class GetXMLTask extends AsyncTask<String, Void, List<Cmd>> {
private Activity context;
public GetXMLTask(Activity context) {
this.context = context;
}
protected void onPostExecute(List<Cmd> videos) {
if (videos != null) {
listViewAdapter = new CustomListViewAdapter(context, videos);
listView.setAdapter(listViewAdapter);
} else {
Toast.makeText(getApplicationContext(),
"XML Video Feed is Null!", Toast.LENGTH_LONG)
.show();
}
}
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
#Override
protected List<Cmd> doInBackground(String... urls) {
List<Cmd> videos = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(
xml.getBytes());
videos = SAXXMLParser.parse(stream);
if (videos != null) {
for (Cmd cmd : videos) {
// String videoName = cmd.getVideoName();
}
}
}
return videos;
}
}
}
}
Two problems:
mPager is defined in onCreate() method and you are trying to use it in another method. You should declare it in class level outside any method.
GetXMLTask is an inner class of ImagePagerAdapter. so it is not visible outside it. move this definition into your main class outside ImagePagerAdapter or use it as ImagePagerAdapter.GetXMLTask