In my android app I'm using a ListView populated by RSSItems taken from a webpage url; the listview shows me only title and pubdate of rssitem.
I would realize that when I click on rssitem of the listview, app shows me an alert dialog showing me in message box the descritpion of the rssitem title.
How can I realize it?
Here the code:
public class MainActivity extends ActionBarActivity{
private ListView listview;
URL url = null;
RssFeed feed = null;
AlertDialog.Builder alert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView);
alert = new AlertDialog.Builder(MainActivity.this);
try {
url = new URL("http://www.unikore.it/index.php/ingegneria-informatica-home?format=feed");
} catch (MalformedURLException e) {
e.printStackTrace();
}
new ReadRssTask().execute(url);
}
private class ReadRssTask extends AsyncTask<URL, Void, RssFeed> {
#Override
protected RssFeed doInBackground(URL... params) {
RssFeed result = null;
URL url = params[0];
if (!TextUtils.isEmpty(url.toString())) {
try {
result = RssReader.read(url);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(RssFeed result) {
if (result != null) {
ArrayList<RssItem> rssItems = (ArrayList<RssItem>) result.getRssItems();
ArrayList<String> arrayList = new ArrayList<String>();
for (final RssItem rssItem : rssItems) {
arrayList.add(rssItem.getTitle()+"\n"+rssItem.getPubDate()+"\n");
ArrayAdapter<String> lista = new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,arrayList);
listview.setAdapter(lista);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
alert.setTitle(listview.getItemAtPosition(position).toString());
alert.setMessage(); //HERE I SHOULD SET THE rssItem.getDescription()
alert.show();
}
});
Log.i("RSS Reader", rssItem.getTitle());
}
}
}
}
}
You need to change here
alert.show();
to
AlertDialog dialog = alert.create(); // You missed this
dialog.show():
Edit:
Remove this from loop and move to onCreate() after your asynctask executed.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
alert.setTitle(listview.getItemAtPosition(position).toString());
alert.setMessage(rssItems.get(position).getDescription()); //HERE YOU SHOULD SET THE rssItem.getDescription()
alert.show();
}
});
Make this ArrayList<RssItem> rssItems public static and use as
rssItems = (ArrayList<RssItem>) result.getRssItems();
Related
Hello guys I have this problem, I want my app to refresh or update the listview items upon clicking a specific spinner item. here is the screenshot
and I have no idea on what I'm gonna do, and this is my code so far :(
public class ViewGrade extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ListView mylistView;
private String subj_code = "";
private String subj_code_lab = "";
private Spinner spinTerm;
private List<GradeList> gradeList = new ArrayList<GradeList>();
private GradeAdapter arrayAdapter;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_grade);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
spinTerm = (Spinner) findViewById(R.id.spinTerm);
String[] Term = new String[]{"Prelim", "Midterm", "Tentative Final"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Term);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinTerm.setAdapter(adapter);
SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
subj_code = preferences.getString("code", "UNKNOWN");
subj_code_lab = preferences.getString("code_lab", "UNKNOWN");
mylistView = (ListView) findViewById(R.id.list);
arrayAdapter = new GradeAdapter(this, gradeList);
mylistView.setAdapter(arrayAdapter);
new loadGrades().execute();
}
public class loadGrades extends AsyncTask<Void, Void, Void>{
String term = spinTerm.getSelectedItem().toString();
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewGrade.this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = null;
try {
url = "http://192.168.22.3/MobileClassRecord/getGrade.php?subj_code="+ URLEncoder.encode(subj_code, "UTF-8")+"&term="+URLEncoder.encode(term, "UTF-8");
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(url, ServiceHandler.GET);
Log.e("Response; ", "> " + json);
if (json != null){
try {
JSONObject object = new JSONObject(json);
if (object != null){
JSONArray grade_array = object.getJSONArray("grade");
for (int i = 0; i < grade_array.length(); i++){
JSONObject grade = (JSONObject) grade_array.get(i);
GradeList grade_list = new GradeList();
grade_list.setName(grade.getString("stud_name"));
grade_list.setGrade(grade.getString("grade"));
grade_list.setRemark(grade.getString("remark"));
gradeList.add(grade_list);
}
}
arrayAdapter.notifyDataSetChanged();
}catch (JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#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_view_grade, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Intent intent = new Intent(ViewGrade.this, SpecificClassRecord.class);
startActivity(intent);
return true;
case R.id.action_add_grade:
Intent intent1 = new Intent(ViewGrade.this, Grade.class);
startActivity(intent1);
}
return super.onOptionsItemSelected(item);
}
}
adapter.notifydatasetChanged() or if you know the specific item inserted/removed, just use adapter.notifyitemInserted/Removed etc.
Add this code in your onClickListener for spinner
Override onItemClick() listener method of the spinner,then inside the method you call adapter.notifydatasetChanged() of the listview
spinTerm.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// change the adapter values if your list is being changedin anyway
arrayAdapter.notifydatasetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
I am trying to update my listview directly after I submit new data from DialogFragment.
But when I call notifyDataSetChanged() it give me an NullPointerException and my app is close.
So this is the scenario what I want
And this is my code
This activity that I use to get data from the server
public class LayoutActivity extends Fragment {
private ListView listview;
private ListItemAdapter theAdapter;
String URL = "http://localhost/api/question/get_newest_except/0/0/15";
ProgressDialog pDialog;
NodeList nodelist;
public LayoutActivity() {
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.layout_main, container,false);
DownloadXML a = new DownloadXML(this);
a.execute(URL);
listview = (ListView) rootview.findViewById(R.id.list01);
return rootview;
}
public class DownloadXML extends AsyncTask<String, Void, Void>{
private LayoutActivity aku;
ArrayList<ListItemObject> data;
public DownloadXML(LayoutActivity aku) {
super();
this.aku = aku;
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
data = new ArrayList<ListItemObject>();
ListItemObject itemData;
try{
for (int temp = 0; temp < nodelist.getLength(); temp++) {
Node nNode = nodelist.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
itemData = new ListItemObject();
itemData.setId(getNode("pb__question__id",eElement));
itemData.setOwner(getNode("pb__question__consumer__id",eElement));
if(!getNode("pb__question__consumer__id",eElement).equalsIgnoreCase("0")){
itemData.setName(getNode("pb__question__consumer__name",eElement));
itemData.setJob(getNode("pb__question__consumer__occupation", eElement));
itemData.setProfilePic(getNode("pb__question__consumer__pp",eElement));
}
itemData.setStatus(getNode("pb__question__title",eElement));
itemData.setExtras(getNode("pb__question__topic__name", eElement));
if(!getNode("att__pict",eElement).isEmpty()){
itemData.setImage(getNode("att__pict", eElement));
}
if(getNode("pb__question__type", eElement).equalsIgnoreCase("1")){
itemData.setOpini(getNode("pb__question__total__opini", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("2") || getNode("pb__question__type", eElement).equalsIgnoreCase("3")){
itemData.setOpini(getNode("pb__question__total__polling", eElement));
}else if(getNode("pb__question__type", eElement).equalsIgnoreCase("4")){
itemData.setOpini(getNode("pb__question__total__rating", eElement));
}
itemData.setTipe(getNode("pb__question__type", eElement));
itemData.setIkuti(getNode("pb__question__total__follow", eElement));
itemData.setSebarkan(getNode("pb__question__total__share", eElement));
data.add(itemData);
}
}
theAdapter = new ListItemAdapter(aku.getActivity(),data);
listview.setAdapter(theAdapter);
}catch(Exception e){
Toast.makeText(getActivity(), "Koneksi dengan server gagal", Toast.LENGTH_SHORT).show();
}
pDialog.dismiss();
}
#Override
protected Void doInBackground(String... Url) {
// TODO Auto-generated method stub
try {
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
nodelist = doc.getElementsByTagName("pb__question");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
}
private static String getNode(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
String result = "";
if(nValue!=null){
result = nValue.getNodeValue();
}
return result;
}
}
and this is the listview adapter, in this adapter I call Dialog from each item
public class ListItemAdapter extends BaseAdapter{
private ArrayList<ListItemObject> itemCards;
private Context mContext;
private FragmentManager mFragmentManager;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ListItemAdapter(FragmentActivity fa, ArrayList<ListItemObject> d) {
super();
this.mContext = fa;
this.itemCards= d;
mFragmentManager = fa.getSupportFragmentManager();
}
#Override
public int getCount() {
return itemCards.size();
}
#Override
public Object getItem(int pos) {
return itemCards.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(final int position, View convertview, ViewGroup parent) {
// TODO Auto-generated method stub
View row=null;
row = convertview;
row = View.inflate(mContext, R.layout.item_layout, null);
final boolean[] mHighlightedPositions = new boolean[itemCards.size()];
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
LinearLayout containerPP = (LinearLayout) row.findViewById(R.id.idCon);
NetworkImageViewCircle fotoPP = (NetworkImageViewCircle) row.findViewById(R.id.pp);
TextView nama = (TextView) row.findViewById(R.id.name);
TextView kerjaan = (TextView) row.findViewById(R.id.jobs);
NetworkImageView gambar = (NetworkImageView) row.findViewById(R.id.feedImage1);
TextView status = (TextView) row.findViewById(R.id.txtStatusMsg);
TextView extra = (TextView) row.findViewById(R.id.txtUrl);
TextView opinion = (TextView) row.findViewById(R.id.opini);
TextView follow = (TextView) row.findViewById(R.id.ikuti);
TextView share = (TextView) row.findViewById(R.id.sebarkan);
Button Opini = (Button) row.findViewById(R.id.Button01);
Button Ikuti = (Button) row.findViewById(R.id.Button02);
Button Sebarkan = (Button) row.findViewById(R.id.Button03);
Ikuti.setTag(position);
Opini.setTag(position);
ListItemObject item = itemCards.get(position);
if(item.getName()==null){
containerPP.setVisibility(View.GONE);
}
if(item.getExtras().equalsIgnoreCase("Pertanyaan Pengguna")){
extra.setVisibility(View.GONE);
}
if(item.getImage()==null){
gambar.setVisibility(View.GONE);
}
if(item.getTipe().equals("4")){
opinion.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.star_icon, 0);
}else if(item.getTipe().equals("2") || item.getTipe().equals("3")){
opinion.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.poll_icon, 0);
}
nama.setText(item.getName());
kerjaan.setText(item.getJob());
fotoPP.setImageUrl(item.getProfilePic(), imageLoader);
status.setText(item.getStatus());
extra.setText(item.getExtras().replaceAll("\n",""));
opinion.setText(item.getOpini());
follow.setText(item.getIkuti());
share.setText(item.getSebarkan());
gambar.setImageUrl(item.getImage(), imageLoader);
if(mHighlightedPositions[position]) {
Ikuti.setBackgroundResource(R.color.ijo);
Ikuti.setTextColor(Color.WHITE);
}else{
Ikuti.setBackgroundResource(R.color.abu2);
Ikuti.setTextColor(Color.BLACK);
}
Opini.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddKomentar(v,position);
}
});
Ikuti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Sebarkan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return row;
}
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
dialog.show(fm, "Dialog");
}
}
and this is the DialogFragment
public class DialogAddOpini extends DialogFragment{
ListItemAdapter theAdapter;
String question_id,owner_id;
EditText question_field;
ProgressDialog pDialog;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.addopini, null);
Bundle mArgs = getArguments();
question_id = mArgs.getString("question");
owner_id = mArgs.getString("owner");
builder.setTitle("Tambahkan Opini");
builder.setView(dialogView)
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
question_field = (EditText) dialogView.findViewById(R.id.content);
SendComment send = new SendComment();
send.execute(question_field.getText().toString());
}
});
Dialog dialog = builder.create();
return dialog;
}
private class SendComment extends AsyncTask<String, Void, Void>{
public SendComment() {
super();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Submitting...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
String content = params[0];
postData(content);
return null;
}
#Override
protected void onPostExecute(Void result) {
theAdapter.notifyDataSetChanged();
pDialog.dismiss();
}
}
public void postData(String content) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/api/opini/add");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pb_question_id", question_id));
nameValuePairs.add(new BasicNameValuePair("owner_id", owner_id));
nameValuePairs.add(new BasicNameValuePair("opini_text", content));
nameValuePairs.add(new BasicNameValuePair("is_anonym", "1"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I call notifyDataSetChanged() inside onPostExecute inside DialogFragment, but it give me NullPointerException.
Can anyone help me?
This the log
Thanks
theAdapter is not initialized in class DialogAddOpini, You need to initialized it before using it in OnPostExecute.
I will prefer to use Listener to return the data from DialogFragment and update List in the Adapter only.
public class DialogAddOpini extends DialogFragment {
private Listener mListener;
public void setListener(Listener listener) {
mListener = listener;
}
static interface Listener {
void returnData();
}
Set the listener while creating Dialog :
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
And return the data like :
#Override
protected void onPostExecute(Void result) {
if (mListener != null) {
mListener.returnData();
}
pDialog.dismiss();
}
And override returnData in Adapter and update the list:
public class ListItemAdapter extends BaseAdapter implements DialogAddOpini.Listener {
#Override
public void returnData() {
notifyDataSetChanged();
}
}
Update :
You have to pass the data and set it in the Adapter's Arraylist to reflect the changes.
Track the position while you show the dialog :
Integer selected_position =-1 ;
public void AddKomentar(View v,int pos){
FragmentActivity activity = (FragmentActivity)(mContext);
FragmentManager fm = activity.getSupportFragmentManager();
ListItemObject item = itemCards.get(pos);
DialogAddOpini dialog = new DialogAddOpini();
Bundle args = new Bundle();
args.putString("question",item.getId());
args.putString("owner",item.getOwner());
dialog.setArguments(args);
selected_position = pos;
dialog.setListener(this);
dialog.show(fm, "Dialog");
}
#Override
public void returnData( String counter) {
itemCards.get(selected_position).setOpini(counter);
notifyDataSetChanged();
selected_position=-1;
}
Hope it helps ツ
I have created an applicaton that shows a listview of some pictures from the internet in ListView. I want to show it in a GridView.I have tried using base adapter in place of list adapter! But that doesn't work as it cant take arg (the arg is in the code)
Can anyone help me to show this images in gridview?
Here is my code.
MainPage.java
public class MainPage extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
setContentView(R. layout. contacts_list);
final List<Model> list = new ArrayList<Model>();
/** This block is for getting the <span id="IL_AD9" class="IL_AD">image url</span> to <span id="IL_AD2" class="IL_AD">download from</span> the server **/
final GetDataFromDB getvalues = new GetDataFromDB();
final ProgressDialog dialog = ProgressDialog.show(MainPage.this,
"", "Gettting values from DB", true);
final CountDownLatch latch = new CountDownLatch(1);
new Thread (new Runnable() {
public void run() {
String response = getvalues.getImageURLAndDesciptionFromDB();
System.out.println("Response : " + response);
dismissDialog(dialog);
if (!response.equalsIgnoreCase("")) {
if (!response.equalsIgnoreCase("error")) {
dismissDialog(dialog);
// Got the response, now split it to get the image Urls and description
String all[] = response.split("##");
for(int k = 0; k < all.length; k++){
String urls_and_desc[] = all[k].split(","); // urls_and_desc[0] contains image url and [1] -> description.
list.add(get(urls_and_desc[1],urls_and_desc[0]));
}
}
} else {
dismissDialog(dialog);
}
latch.countDown();
}
}).start();
/*************************** GOT data from Server ********************************************/
try {
latch.await();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this, list);
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Intent intent = new Intent(MainPage.this, ViewImage.class);
Model model = list.get(position);
String myURL = model.getURL();
intent.putExtra("image", myURL);
startActivity(intent);}
});
}
public void dismissDialog(final ProgressDialog dialog){
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
private Model get(String s, String url) {
return new Model(s, url);
}
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder.setTitle("Exit!");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to leave?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainPage.this.finish();
}
})
.setNegativeButton("No",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();
}
// your code.
}
MyCustomArrayAdapter.java
public class MyCustomArrayAdapter extends ArrayAdapter<Model> {
private final Activity context;
private final List<Model> list;
public MyCustomArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.list_layout_relative, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected ImageView image;
protected ProgressBar pb;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.list_layout_relative, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.text.setTextColor(Color.BLACK);
viewHolder.image = (ImageView) view.findViewById(R.id.image);
viewHolder.image.setVisibility(View.GONE);
viewHolder.pb = (ProgressBar) view.findViewById(R.id.progressBar1);
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.image.setTag(list.get(position).getURL());
holder.image.setId(position);
PbAndImage pb_and_image = new PbAndImage();
pb_and_image.setImg(holder.image);
pb_and_image.setPb(holder.pb);
new DownloadImageTask().execute(pb_and_image);
return view;
}
}
Model.java
public class Model {
private String name;
private String url;
public Model(String name, String url) {
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getURL() {
return url;
}
public void setURL(String url) {
this.url = url;
}
}
i wanna ask something else too.kinda off topic.. i am downlaoding images from the urls and display in gridview. but it downloads huge images that takes lots of data. is there anyway i can download thumbnails to that images to reduce data usage?
same code but instead of extend listActivity extend normal activity and defining xml with GridView with id foo or what ever you want.
GridView foo = (GridView) findViewById(R.id.foo);
ArrayAdapter<Model> adapter = new MyCustomArrayAdapter(this, list);
foo.setAdapter(adapter);
I have an app that propogates a spinner from a website inside an AsyncTask. Without a ProgressDialog, I am stuck with an empty spinner until it loads. With a ProgressDialog, the network operation never finishes and the ProgressDialog stays up forever. Here is my code:
class TheaterGetter extends AsyncTask<Void, Void, Document> {
private Context context;
private ProgressDialog dialog;
public TheaterGetter(Context context) {
this.context = context;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setMessage(((Activity) context).getString(R.string.loading_theaters));
dialog.setCancelable(false);
dialog.show();
}
protected Document doInBackground(Void...voids) {
Document doc = null;
try {
doc = Jsoup.connect("http://landmarkcinemas.com").timeout(10000).get();
} catch (IOException e) {
Log.e("landmark cinemas connection error", e.getMessage());
}
return doc;
}
protected void onPostExecute(Document doc) {
Element allOptions = doc.select("select[id=campaign").first();
Elements options = allOptions.getElementsByTag("option");
options.remove(0);
TreeMap<String, String> theaters = new TreeMap<String, String>();
for (Element option:options) {
theaters.put(option.html(), option.attr("value"));
}
final TreeMapSpinAdapter adapter = new TreeMapSpinAdapter(context, android.R.layout.simple_spinner_item, theaters);
final Spinner spinner = (Spinner) ((Activity) context).findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
MainActivity.setTheater((String) adapter.getItem(pos));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
dialog.dismiss();
}
}
Just rearrange the dismiss dialog line as follows :
protected void onPostExecute(Document doc) {
dialog.dismiss(); // rearranged
Element allOptions = doc.select("select[id=campaign").first();
Elements options = allOptions.getElementsByTag("option");
options.remove(0);
TreeMap<String, String> theaters = new TreeMap<String, String>();
for (Element option:options) {
theaters.put(option.html(), option.attr("value"));
}
final TreeMapSpinAdapter adapter = new TreeMapSpinAdapter(context, android.R.layout.simple_spinner_item, theaters);
final Spinner spinner = (Spinner) ((Activity) context).findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
MainActivity.setTheater((String) adapter.getItem(pos));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
i have a listview builded from xml file by an lazyadapter (baseadpter)
for example: urlxml --> parser ---> baseadapter ---> listview
when i modified xml file on server i would like to refresh listview and see rows changed in it. By the way im using lib "pull to refresh".
When i pull to refresh i got new rows togheter old rows.
Do i have to delete listview content first and repeat this:
urlxml --> parser ---> baseadapter ---> listview
what is wrong?
EDIT woth some code
my adapter
public class LazyAdapter extends BaseAdapter {
private Activity activity;
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>> ();
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<ArrayList<String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.get(0).size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.elenco_articoli_items, null);
String Tt = data.get(0).get(position);
String URl = data.get(1).get(position);
TextView text=(TextView)vi.findViewById(R.id.title);;
ImageView image=(ImageView)vi.findViewById(R.id.image);
text.setText(Html.fromHtml(Tt));
imageLoader.DisplayImage(URl, image,1);
return vi;
}
}
my main activity
public class Lista_articoli_categoria extends Activity {
ArrayList<String> images = new ArrayList<String> ();
ArrayList<String> title = new ArrayList<String> ();
ArrayList<String> author = new ArrayList<String> ();
ArrayList<String> description = new ArrayList<String> ();
private LazyAdapter adapter;
private RefreshableListView mListView;
Parser task = new Parser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.elenco_articoli);
try {
task.execute();
final RefreshableListView list = (RefreshableListView) findViewById(R.id.refreshablelistview);
adapter= new LazyAdapter(this, fill_data(task.get()));
mListView = list;
list.setAdapter(adapter);
list.setOnUpdateTask(new OnUpdateTask() {
public void updateBackground() {
refresh_data();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void updateUI() {
adapter.notifyDataSetChanged();
}
public void onUpdateStart() {
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*
TODO
*/
}
});
}
#Override
public void onDestroy()
{
mListView.setAdapter(null);
super.onDestroy();
}
public ArrayList<ArrayList<String>> fill_data(ArrayList<Struttura_rss> Datidaxml){
ArrayList<ArrayList<String>> rec = new ArrayList<ArrayList<String>> ();
for(int i=0;i<Datidaxml.size();i++){
Struttura_rss p = Datidaxml.get(i);
title.add(p.getTitle());
images.add(p.getImage());
description.add(p.getArticolo());
author.add(p.getAuthor());
}
rec.add (title);
rec.add (images);
rec.add (description);
rec.add (author);
return rec;
}
public void refresh_data(){
try {
Parser task = new Parser();
task.execute();
adapter= new LazyAdapter(this, fill_data(task.get()));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
If you look at the example, you should understand easily...
Link: https://github.com/chrisbanes/Android-PullToRefresh/blob/master/sample/src/com/handmark/pulltorefresh/samples/PullToRefreshListActivity.java
On the refreshn you have to download only the new items (by exemple by sending a timestamp or an id to the webservice)
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
//Go to webservice
} catch (InterruptedException e) {
}
return mStrings;
}
And then, parse only the new items and add them here:
#Override
protected void onPostExecute(String[] result) {
mListItems.addFirst("Added after refresh...");
mAdapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed.
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
EDIT: if you cannot download only the needed items (RSS feed) download evrything and add the correct items in onPostExecute.
if(!isALreadyInTheList(currentItem))
mListItems.addFirst(currentItem);
else
doNothing();