Android Development: Custom ListAdapter in Fragment - java

I got the following Fragment
public static class DummySectionFragment extends Fragment {
ListView msgList;
ArrayList<StundenplanDetail> details;
AdapterView.AdapterContextMenuInfo info;
public void addVertretung (String Fach, String Raum, String Farbe) {
StundenplanDetail Detail;
Detail = new StundenplanDetail();
Detail.setFach(Fach);
Detail.setRaum(Raum);
Detail.setFarbe(Farbe);
details.add(Detail);
}
/**
* The fragment argument representing the section number for this
* fragment.
*/
XMLParser parser = new XMLParser();
String xml = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public void loadArray (String dayArray) {
}
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try{
byte[] inputBuffer = new byte[20000];
File inputFile = new File("sdcard/Android/data/com.approfi.woehlerschule/data.woehler");
FileInputStream fileInputStream = new FileInputStream(inputFile);
fileInputStream.read(inputBuffer);
xml = new String(inputBuffer);
fileInputStream.close();
}catch(IOException e){
Log.d("Fehler:", e.toString());
}
View rootView = inflater.inflate(
R.layout.fragment_stundenplan_dummy, container, false);
if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("1")){
int splitpos1 = xml.indexOf("<Montag>");
int splitpos2 = xml.indexOf("</Montag>") + 9;
String xml2 = xml.substring(splitpos1, splitpos2);
org.w3c.dom.Document doc = parser.getDomElement(xml2);
NodeList nl = doc.getElementsByTagName("Stunde");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element)nl.item(i);
String Fach = parser.getValue(e, "Fach"); // name child value
String Raum = parser.getValue(e, "Raum"); // cost child value
String Farbe = parser.getValue(e, "Farbe"); // description child value
Log.d("Fail:", Fach + Raum + Farbe);
}
}
/*if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("2")){
ListView listViewStundenplan = (ListView) rootView.findViewById(R.id.listViewStundenplan);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_stundenplan, dienstagArray);
listViewStundenplan.setAdapter(arrayAdapter);
}
if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("3")){
ListView listViewStundenplan = (ListView) rootView.findViewById(R.id.listViewStundenplan);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_stundenplan, mittwochArray);
listViewStundenplan.setAdapter(arrayAdapter);
}
if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("4")){
ListView listViewStundenplan = (ListView) rootView.findViewById(R.id.listViewStundenplan);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_stundenplan, donnerstagArray);
listViewStundenplan.setAdapter(arrayAdapter);
}
if(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)).equals("5")){
ListView listViewStundenplan = (ListView) rootView.findViewById(R.id.listViewStundenplan);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_stundenplan, freitagArray);
listViewStundenplan.setAdapter(arrayAdapter);
}
*/
msgList = (ListView) rootView.findViewById(R.id.listViewStundenplan);
msgList.setAdapter(new StundenplanAdapter(details, this));
return rootView;
}
}
And that Adapter for my List View
public class StundenplanAdapter extends BaseAdapter {
private ArrayList<StundenplanDetail> _data;
Context _c;
StundenplanAdapter (ArrayList<StundenplanDetail> data, Context c){
_data = data;
_c = c;
}
public int getCount() {
return _data.size();
}
public Object getItem(int position) {
return _data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)_c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item_stundenplan, null);
}
TextView fachText = (TextView)v.findViewById(R.id.textViewStundenplanFach);
TextView raumText = (TextView)v.findViewById(R.id.textViewStundenplanRaum);
View colorBlock = (View)v.findViewById(R.id.colorBlockStundenplan);
StundenplanDetail msg = _data.get(position);
fachText.setText(msg.fach);
raumText.setText(msg.raum);
colorBlock.setBackgroundColor(37000000);;
return v;
}
}
Now the problem is, that eclipse tells me that The constructor StundenplanAdapter(ArrayList<StundenplanDetail>, Stundenplan.DummySectionFragment) is undefined but i want to use my custom adapter. Every thing works. The List View in my Fragment and the Custom adapter but not if I want to use the custom adapter in my fragment-listview
I hope you can help me
thanks in advance,
MoBr114

Send your FragmentActivity context to your Adapter not Fragment itself!
Try :
msgList.setAdapter(new StundenplanAdapter(details, getActivity()));

You are passing the wrong argument to the Adapter in msgList.setAdapter(). It looks for the context of the Activity non the instance of the class DummySectionFragment.

Related

How to to show call log in ListView on Fragment?

I need to show call log in ListView on Fragment
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1,
R.id.tvNameMain, conNames));
return rootView;
And All Code
private ListView mListView;
private ArrayList<String> conNames;
private ArrayList<String> conNumbers;
private ArrayList<String> conTime;
private ArrayList<String> conDate;
private ArrayList<String> conType;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_recents, container, false);
mListView = (ListView)rootView.findViewById(R.id.list);
conNames = new ArrayList<String>();
conNumbers = new ArrayList<String>();
conTime = new ArrayList<String>();
conDate = new ArrayList<String>();
conType = new ArrayList<String>();
Cursor curLog = getAllCallLogs(getActivity().getContentResolver());
setCallLogs(curLog);
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1,
R.id.tvNameMain, conNames));
return rootView;
}
Class MyAdapter
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource, int textViewResourceId,
ArrayList<String> conNames) {
super(context, resource, textViewResourceId, conNames);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = setList(position, parent);
return row;
}
private View setList(int position, ViewGroup parent) {
LayoutInflater inf = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inf.inflate(R.layout.liststyle, parent, false);
TextView tvName = (TextView) row.findViewById(R.id.tvNameMain);
TextView tvNumber = (TextView) row.findViewById(R.id.tvNumberMain);
TextView tvTime = (TextView) row.findViewById(R.id.tvTime);
TextView tvDate = (TextView) row.findViewById(R.id.tvDate);
TextView tvType = (TextView) row.findViewById(R.id.tvType);
tvName.setText(conNames.get(position));
tvNumber.setText(conNumbers.get(position));
tvTime.setText("( " + conTime.get(position) + "sec )");
tvDate.setText(conDate.get(position));
tvType.setText("( " + conType.get(position) + " )");
return row;
}
}
Class CallLog
private void setCallLogs(Cursor curLog) {
while (curLog.moveToNext()) {
String callNumber = curLog.getString(curLog
.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
conNumbers.add(callNumber);
String callName = curLog
.getString(curLog
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
if (callName == null) {
conNames.add("Unknown");
} else
conNames.add(callName);
String callDate = curLog.getString(curLog
.getColumnIndex(android.provider.CallLog.Calls.DATE));
SimpleDateFormat formatter = new SimpleDateFormat(
"dd-MMM-yyyy HH:mm");
String dateString = formatter.format(new Date(Long
.parseLong(callDate)));
conDate.add(dateString);
String callType = curLog.getString(curLog
.getColumnIndex(android.provider.CallLog.Calls.TYPE));
if (callType.equals("1")) {
conType.add("Incoming");
} else
conType.add("Outgoing");
String duration = curLog.getString(curLog
.getColumnIndex(android.provider.CallLog.Calls.DURATION));
conTime.add(duration);
}
}
Class Cursor
public static Cursor getAllCallLogs(ContentResolver cr) {
// reading all data in descending order according to DATE
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Uri callUri = Uri.parse("content://call_log/calls");
Cursor curCallLogs = cr.query(callUri, null, null, null, strOrder);
return curCallLogs;
}
If you want to use setListAdapter your Fragment should extend ListFragment. but in your case changing it to mListView.setAdapter([...]) should do the trick
Change
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, R.id.tvNameMain, conNames));
To
mListView.setAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, R.id.tvNameMain, conNames));

Creating dynamic ListView using BaseAdapter class not working

I am trying to create a dynamic List View using BaseAdapter class.
Below is the code that I am using here.
Code for Main Activity:
public class DisplayFlightsActivity extends AppCompatActivity {
String str_jsonresponse,fare,carrier,number,arrivaltime,departuretime,origin,destination;
ArrayList<String> listitem = new ArrayList<String>();
ListView listView;
//MyBaseAdapter baseAdapter;
Context context = DisplayFlightsActivity.this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
str_jsonresponse = extras.getString(DisplaySummaryActivity.STR_JSONRESPONSE);
try{
JSONObject root_jsonresponse = new JSONObject(str_jsonresponse);
JSONObject l1_jsonobject = root_jsonresponse.optJSONObject("trips");
JSONArray l2_jsonarray = l1_jsonobject.optJSONArray("tripOption");
for (int i=0;i < l2_jsonarray.length();i++)
{
JSONObject l21_jsonobject = l2_jsonarray.getJSONObject(i);
fare = l21_jsonobject.getString("saleTotal");
JSONArray l3_jsonarray = l21_jsonobject.optJSONArray("slice");
for (int j=0;j < l3_jsonarray.length();j++)
{
JSONObject l4_jsonobject = l3_jsonarray.getJSONObject(j);
JSONArray l5_jsonarray = l4_jsonobject.optJSONArray("segment");
for(int k=0;k < l5_jsonarray.length();k++)
{
JSONObject l6_jsonobject = l5_jsonarray.getJSONObject(k);
JSONObject l7_jsonobject = l6_jsonobject.optJSONObject("flight");
carrier = l7_jsonobject.getString("carrier");
number = l7_jsonobject.getString("number");
JSONArray l8_jsonarray = l6_jsonobject.optJSONArray("leg");
for(int m=0;m < l8_jsonarray.length(); m++)
{
JSONObject l9_jsonobject = l8_jsonarray.getJSONObject(m);
arrivaltime = l9_jsonobject.getString("arrivalTime");
departuretime = l9_jsonobject.getString("departureTime");
origin = l9_jsonobject.getString("origin");
destination = l9_jsonobject.getString("destination");
}
}
}
listitem.add(fare);
listitem.add(carrier);
listitem.add(number);
listitem.add(arrivaltime);
listitem.add(departuretime);
listitem.add(origin);
listitem.add(destination);
}
}
catch(JSONException JE){
JE.printStackTrace();
}
catch (Exception err){
err.printStackTrace();
}
MyBaseAdapter baseAdapter = new MyBaseAdapter(context,listitem);
listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(baseAdapter);
setTitle("Results Page");
//setContentView(R.layout.activity_display_flights);
}
}
Code for Base Adapter class:
class MyBaseAdapter extends BaseAdapter {
Context context;
ArrayList<String> listitem = new ArrayList<>();
LayoutInflater inflater = null;
public MyBaseAdapter(Context context, ArrayList<String> listitem) {
this.context = context;
this.listitem = listitem;
inflater = LayoutInflater.from(this.context);
}
public int getCount() {
return listitem.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.listview_item_layout, null);
TextView carrier = (TextView) vi.findViewById(R.id.layout_textview1);
TextView number = (TextView) vi.findViewById(R.id.layout_textview2);
TextView arrivaltime = (TextView) vi.findViewById(R.id.layout_textview6);
TextView departuretime = (TextView) vi.findViewById(R.id.layout_textview7);
TextView saletotal = (TextView) vi.findViewById(R.id.layout_textview8);
String str_carrier = listitem.get(position).toString();
String str_number = listitem.get(position).toString();
String str_arrivaltime = listitem.get(position).toString();
String str_departuretime = listitem.get(position).toString();
String str_saletotal = listitem.get(position).toString();
carrier.setText(str_carrier);
number.setText(str_number);
arrivaltime.setText(str_arrivaltime);
departuretime.setText(str_departuretime);
saletotal.setText(str_saletotal);
return vi;
}
}
My Problem is: The Base Adapter class is never getting invoked for me. I was trying to debug, but the control never goes inside of BaseAdapter class. I am able to parse the JSON Data and put it in ListItem but I am not able to access Base Adapter class.
Is there anything I am doing wrong? Can anybody please review the code and let me know why it is not working.
Thanks in advance!
I was able to solve the problem by adding the line setContentView(R.layout.activity_display_flights); above, like this --
baseAdapter = new MyBaseAdapter(context,listitem);
setTitle("Results Page");
setContentView(R.layout.activity_display_flights);
listView = (ListView) findViewById(R.id.list_view);
listView.setBackgroundResource(R.drawable.androidbckgrnd1);
listView.setAdapter(baseAdapter);
Earlier the ListView instance was coming as null. Now that issue has been resolved.

Array Adapter doesn't call GetView

I have
public class MainActivity extends FragmentActivity
I wrote Loader class which implements AsyncResponse:
public class Loader implements AsyncResponse {
public Activity contextActivity;
Loader(Activity context) {
this.contextActivity = context;
}
Class "Loader" has method "DrawTabInfo" which calling from AsyncResponse callback.
public void drawTabInfo(String jsonBlob, int tabId)
{
JSONObject dataJsonObj;
PullToRefreshListView list = null;
try {
dataJsonObj = new JSONObject(jsonBlob);
JSONArray jsonData = dataJsonObj.getJSONArray("steals");
ArrayList<JSONObject> data = new ArrayList<JSONObject>();
for (int i=0;i<jsonData.length();i++){
data.add(jsonData.getJSONObject(i));
}
Adapter adapter = new Adapter(contextActivity, data);
LayoutInflater inflater = LayoutInflater.from(contextActivity);
if (tabId == 0) {
View view = inflater.inflate(R.layout.listviewlayout, null, false);
list = (PullToRefreshListView) view.findViewById(R.id.listView);
}
if (tabId == 1) {
View view = inflater.inflate(R.layout.listviewlayout2, null, false);
list = (PullToRefreshListView) view.findViewById(R.id.listView2);
}
list.setAdapter(adapter);
adapter.setNotifyOnChange(true);
Log.d("COUNT") shows - "4", what means array is built fine.
public class Adapter extends ArrayAdapter<JSONObject> {
private final Activity context;
private final ArrayList<JSONObject> profiles;
public String header;
public String preText;
public String imageURL;
static class ViewHolder {
public TextView header;
public ImageView image;
public TextView preText;
public LinearLayout linearItemLayout;
}
public Adapter(Activity context, ArrayList<JSONObject> array) {
super(context, R.layout.tab1_list_layout, array);
Log.d("ADAPTER", "SETTING ADAPTER");
this.context = context;
this.profiles = array;
Log.d("COUNT", "" + profiles.size());
}
#Override
public int getCount()
{
return profiles.size();
}
My getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Log.i("GetView Log", "Adapters GetView hasbeen called");// thats never calling
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.tab1_list_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.linearItemLayout = (LinearLayout) rowView.findViewById(R.id.linearItemLayout);
viewHolder.header = (TextView) rowView.findViewById(R.id.itemHeader);
viewHolder.image = (ImageView) rowView.findViewById(R.id.itemPreImage);
viewHolder.preText = (TextView) rowView.findViewById(R.id.itemPreText);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
JSONObject item = null;
try {
item = profiles.get(position);
header = item.getString("header");
preText = item.getString("previewText");
imageURL = item.getString("previewImageUrl");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("ADAPTER LOG", header);
holder.header.setText(header);
holder.preText.setText(preText);
int headerHeight = (int) Math.round(header.length() * 1.5);
holder.linearItemLayout.setMinimumHeight(40 + headerHeight + preText.length());
Picasso.with(context).setIndicatorsEnabled(true);
Picasso.with(context).load(imageURL).resize(140,100).into(holder.image);
return rowView;
}
In MainActivity i calling, where "this" = MainActivity;
Loader loader = new Loader(this);
loader.loadTabInfo(0);
Method getView never calling. What I'am doing wrong?
UPD:
Solved:
public void drawTabInfo(String jsonBlob, int tabId)
{
JSONObject dataJsonObj;
PullToRefreshListView list = null;
try {
dataJsonObj = new JSONObject(jsonBlob);
JSONArray jsonData = dataJsonObj.getJSONArray("steals");
ArrayList<JSONObject> data = new ArrayList<JSONObject>();
for (int i=0;i<jsonData.length();i++){
data.add(jsonData.getJSONObject(i));
}
Adapter adapter = new Adapter(contextActivity, data);
//LayoutInflater inflater = LayoutInflater.from(contextActivity);
if (tabId == 0) {
//View view = inflater.inflate(R.layout.listviewlayout, null, false);
list = (PullToRefreshListView) contextActivity.findViewById(R.id.listView);
Your code is fine .. just you need a little bit change in get view method
add a return statement.. like return rowView;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
Log.d("GETVIEaW", "GETVIEW");
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.tab1_list_layout, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.linearItemLayout = (LinearLayout) rowView.findViewById(R.id.linearItemLayout);
viewHolder.header = (TextView) rowView.findViewById(R.id.itemHeader);
viewHolder.image = (ImageView) rowView.findViewById(R.id.itemPreImage);
viewHolder.preText = (TextView) rowView.findViewById(R.id.itemPreText);
rowView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) rowView.getTag();
}
viewHolder.preText.setText("Type your name");
return rowView;
}
Are you sure that Log.d() is not called? You may want to change logging scope, usually default scope is info and it doesn't show debug messages. You can try to use Log.i() or change scope.
Try posting your adapter.setNotifyOnChange(true); to handler. Follow this link

invalidateViews() and notifyDataSetChanged() doesnt work for me

i using ListView in fragment. I have one asynctask to download json data from remote server. I try refresh programmatically my displayed adapter/listview in onPostExecute function but it doesn't work for me.
My main activity with three fragments, three listview, three adapter and one async task.
public class ContactsActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
private static List<Item> BackList = new ArrayList<Item>();
private static List<Item> BackList2 = new ArrayList<Item>();
private static List<Item> BackList3 = new ArrayList<Item>();
private static ListView ListView;
private static Context activity;
public static String HASH;
private static final String[] timestamp = {"0"};
private static WeatherAdapter adapter;
private static int fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
Intent myIntent= getIntent();
HASH = myIntent.getStringExtra("HASH");
Log.d("Intent - contactActivity", HASH);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
(new PrefetchData()).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.contacts, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
fragment = position;
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
int index = getArguments().getInt(ARG_SECTION_NUMBER);
fragment = index;
activity = getActivity();
ListView listview1 = (ListView) rootView.findViewById(R.id.listView);
switch(fragment){
case 1:
adapter = new WeatherAdapter(activity, R.layout.listview_item_row, BackList);
listview1.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
Intent rozmowa = new Intent(getActivity(), Incotalk.class);
rozmowa.putExtra("HASH", HASH);
startActivity(rozmowa);
}
});
break;
case 2:
adapter = new WeatherAdapter(activity, R.layout.listview_item_row2, BackList2);
break;
case 3:
adapter = new WeatherAdapter(activity, R.layout.listview_item_row3, BackList3);
break;
}
listview1.setAdapter(adapter);
ListView = listview1;
return rootView;
}
}
/**
* Async Task to make http call
*/
private class PrefetchData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// before making http calls
}
#Override
protected Void doInBackground(Void... arg0) {
final String id = HASH;
final String url = "http://freshfrog.pl/projects/talk.php?user="+id+"&t=" + timestamp[0];
Log.d("BBB","start");
try {
String page = new Communicator().executeHttpGet(url);
JSONObject jsonObject = new JSONObject(page);
timestamp[0] = jsonObject.getString("t");
HASH = jsonObject.getJSONObject("s").getString("hash");
JSONArray oczekujacy = jsonObject.getJSONArray("m");
// wiadomosci
BackList.clear(); // czyści przed odświerzeniem
BackList2.clear();
BackList3.clear();
for (int i=oczekujacy.length()-1; i>0; i--) {
JSONObject actor = oczekujacy.getJSONObject(i);
String message = actor.getString("m");
String hash = actor.getString("n");
String t = actor.getString("t");
int l = BackList.size();
Boolean jest = false;
for(int j=0; j<l; j++){
Item item = BackList.get(j);
if(!item.isSection()){
ContactItem contactItem= (ContactItem) item;
if( (contactItem.hash).equals(hash) ){
jest = true;
break;
}
}
//Log.d("bbb", BackList.get(j).hash);
}
if(!jest && !hash.equals(id)) BackList.add(
new ContactItem(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
message,
hash));
}
// znajomi
BackList2.add(new SectionItem("Otrzymane zaproszenia"));
oczekujacy = jsonObject.getJSONObject("f").getJSONObject("p").getJSONArray("sending");
for (int i=0; i<oczekujacy.length(); i++) {
JSONObject actor = oczekujacy.getJSONObject(i);
String name = actor.getString("name");
String hash = actor.getString("hash");
String avatar = actor.getString("avatar");
BackList2.add(new ContactItem(getBitmapFromURL(avatar) , name, hash) );
}
// szukaj
BackList3.add(new SectionItem("Znajomi"));
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
BackList3.add(new ContactItem(
BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher),
name,
phoneNumber) );
}
} catch (Exception e) {
Log.d("BBB", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/* gdy skończy */
adapter.notifyDataSetChanged();
ListView listview2 = (ListView) findViewById(R.id.listView);
listview2.invalidateViews();
//Toast.makeText(ContactsActivity.this, "coś przyszło", Toast.LENGTH_SHORT).show();
Log.d("BBB", "powinno sie odswieżyc");
new PrefetchData().execute();
}
}
}
My custom adapter
public class WeatherAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
List<Item> data = null;
private LayoutInflater vi;
public WeatherAdapter(Context context, int layoutResourceId, List<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
SectionHolder holder2 = null;
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
Item i = data.get(position);
if(row == null){
if(!i.isSection()){
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
ContactItem contactItem = (ContactItem)i;
holder.txtTitle.setText(contactItem.title);
holder.imgIcon.setImageBitmap(contactItem.icon);
}else{
row = inflater.inflate(R.layout.listview_header_row, parent, false);
holder2 = new SectionHolder();
holder2.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder2);
SectionItem sectionItem = (SectionItem)i;
holder2.txtTitle.setText(sectionItem.title);
}
}
else
{
if(!i.isSection()){
//holder = (WeatherHolder) row.getTag();
}else{
//holder2 = (SectionHolder) row.getTag();
}
}
return row;
}
public void update(List<Item> newlist) {
Log.d("bbb","aktualizacja listview");
data.clear();
data.addAll(newlist);
this.notifyDataSetChanged();
}
#Override
public void notifyDataSetChanged() // Create this function in your adapter class
{
//notifySetDataChanged()
super.notifyDataSetChanged();
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
static class SectionHolder
{
TextView txtTitle;
}
}
the part of the "if(row == null){" should only contain initializations of the views and the viewHolders.
it shouldn't contain any setting of data to the views.
after this part ( after the "else {...}" ) , you should update the views with the new data .
here's my fix to your code (looks ugly, but should work) :
...
int type=getViewType();
switch(type)
{
case 0:
if(row == null)
{
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
holder = (WeatherHolder) row.getTag();
ContactItem contactItem = (ContactItem)i;
holder.txtTitle.setText(contactItem.title);
holder.imgIcon.setImageBitmap(contactItem.icon);
break;
case 1:
if(row == null)
{
row = inflater.inflate(R.layout.listview_header_row, parent, false);
holder2 = new SectionHolder();
holder2.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder2);
}
else
holder2 = (SectionHolder) row.getTag();
SectionItem sectionItem = (SectionItem)i;
holder2.txtTitle.setText(sectionItem.title);
break;
}
return row;
...
... int getViewType(...) {... return i.isSection()? 1:0;}
... int getViewTypeCount(){return 2;}
btw, you should really watch the lecture "the world of listView" . they have great tips that will make your code much better.
for example, you can use getViewTypeCount , getViewType, getItem, as shown on the API .
to view your code i see that you have started your async execution again on postExcecute
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/* gdy skończy */
adapter.notifyDataSetChanged();
ListView listview2 = (ListView) findViewById(R.id.listView);
listview2.invalidateViews();
//Toast.makeText(ContactsActivity.this, "coś przyszło", Toast.LENGTH_SHORT).show();
Log.d("BBB", "powinno sie odswieżyc");
new PrefetchData().execute();
}
also clearing data inside your doBackground
To get changes on your data you should not clear your data just get updates records and notify your adapeter
try to change the method data.addAll(newlist) by using addall(newlist, data);
inside addall method add one by one the list of element. this way it should work.
i had the same problem and i correct it the way i explained.

Data couldn't be retrieved from an internet

I want to retrieve the data from particular website( "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore ),
however, I couldn't managed to retrieve it.
I think there is something wrong with my code but I not sure which part gone wrong.
Could anyone help me out?
This is my coding.
It contains of the spinner date filtering as well.
public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {
List<String> browseby = new ArrayList<String>();
Date d = new Date();
String[] dates = { "Today", "Tomorrow", "This Week",
};
ArrayList<String> browse = new ArrayList<String>();
ArrayList<String> mPostingData = new ArrayList<String>();
Spinner s1;
ListView listview;
CustomAdapter cus;
// All static variables
static final String URL = "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore";
// XML node keys
static final String KEY_EVENT = "event"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_START_TIME = "start_time";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_EVENT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
R.id.title,
R.id.startTime });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title))
.getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
startActivity(in);
}
});
listview = (ListView) findViewById(R.id.listView1);
s1 = (Spinner) findViewById(R.id.spinner1);
for (int i = 0; i < browseby.size(); i++) {
browse.add(browseby.get(i));
}
// aa = new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
s1.setOnItemSelectedListener(this);
mPostingData = browse;
for (int i = 0; i < mPostingData.size(); i++) {
if (mPostingData.size() > 0)
Log.i("Datas", mPostingData.get(i));
}
cus = new CustomAdapter(this, 0);
setListAdapter(cus);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, dates);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// listview.setFilterText(Category[position]);
String Text = s1.getSelectedItem().toString();
cus.getFilter().filter(Text);
cus.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> parent) {
// listview.setFilterText("");
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Toast.makeText(this, "You have selected " + mPostingData.get(position),
Toast.LENGTH_SHORT).show();
}
class CustomAdapter extends ArrayAdapter<String> {
public void setData(ArrayList<String> mPpst) {
mPostingData = mPpst;// contains class items data.
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected void publishResults(CharSequence constraint,
FilterResults start_time) {
if (start_time != null && start_time.count >= 0) {
setData((ArrayList<String>) start_time.values);
} else {
setData(browse);// set original values
}
notifyDataSetInvalidated();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if(constraint=="Today") {
constraint = constraint.toString();
CharSequence s = DateFormat.format("yyyy-MM-dd ", d.getTime());
ArrayList<String> foundItems = new ArrayList<String>();
if (browse != null) {
for (int i = 0; i < browse.size(); i++) {
if (browse.get(i).contains(s)){
System.out.println("My datas" + browse.get(i));
foundItems.add(browse.get(i));
} else {
}
}
}
result.count = foundItems.size();// search results found
// return count
result.values = foundItems;// return values
} else {
result.count = -1;// no search results found
}
return result;
}
};
}
LayoutInflater mInflater;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
vh.t1 = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(vh);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
vh = (ViewHolder) convertView.getTag();
}
if (mPostingData.size() > 0)
vh.t1.setText(mPostingData.get(position));
return convertView;
}
}
static class ViewHolder {
TextView t1;
}
}
have you added this permission in your manifest file
<uses-permission
android:name="android.permission.INTERNET"
></uses-permission>

Categories

Resources