MainActivity.class:
public class MainActivity extends ListActivity {
public static final String TITLE = "title";
public static final String SUBTITLE = "subtitle";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/// setContentView(R.layout.activity_main);
setListAdapter(createAdapter());
}
protected Map<String, String> createElement(String title, String subtitle)
{
Map<String, String> result = new HashMap<String, String>();
result.put(TITLE, title);
result.put(SUBTITLE, subtitle);
return result;
}
public List<Map<String, String>> getData()
{
List<Map<String, String>> result = new ArrayList<Map<String,String>>();
result.add(createElement("Hello", ""));
result.add(createElement("Hello2", ""));
result.add(createElement("Hello3", ""));
return result;
}
public ListAdapter createAdapter()
{
SimpleAdapter adapter = new SimpleAdapter(this, getData(),
android.R.layout.simple_list_item_2,
new String[]{TITLE, SUBTITLE, },
new int[]{android.R.id.text1, android.R.id.text2});
adapter.areAllItemsEnabled();
return adapter;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent i = null;
switch (position)
{
case 0:
i = new Intent(this, GalleryUrlActivity.class);
break;
case 1:
i = new Intent(this, GalleryFileActivity.class);
break;
case 2:
i = new Intent(this, SonEklenen.class );
break;
}
startActivity(i);
}
}
How to add edittext and button inside listview
i want to add a button and edittext inside MainActivity class. how can i do that?
Please read this tutorial first: http://www.vogella.com/articles/AndroidListView/article.html. There is a section specifically of developing custom adapters which is what you want to do, but you need to have more information on how ListView works to understand it so I recommend reading the whole tutorial.
Related
I want to create multiple tabs depending on number of items retained from API. I have successfully created tabs, and swiping over is working fine, but the issue is that for instance, let's say I have 3 tabs. When they are all created, first and second tabs are empty, and the third has data, when I swipe back to 1, I see the data loaded too, but never on the second tab. When the tabs are 2, neither show data. Here is my code:
Activity
public class MenuActivity extends AppCompatActivity {
private ViewPager tabsPager;
private Toolbar toolbar;
private ImageView toolbarImageView;
private TextView subTitleView, titleView, priceCounterView, itemsCounterView;
private RatingBar ratingBar;
private TabLayout tabLayout;
private LinearLayout cartButton;
private AVLoadingIndicatorView avi;
private MenuPagerAdapter tabsAdapter;
public List<MenuType> menuTypes = new ArrayList<>();
public List<MenuItem> menuItems = new ArrayList<>();
private Restaurant restaurant;
private Context context;
private CollapsingToolbarLayout collapsingToolbarLayout;
private AppBarLayout appBarLayout;
private int i = -1;
public List<Fragment> fragments = new ArrayList<>();
private int cartCount = 0;
private int priceCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
context = this;
tabsPager = (ViewPager) findViewById(R.id.tabs_pager);
toolbar = (Toolbar) findViewById(R.id.toolbar);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
avi = (AVLoadingIndicatorView) findViewById(R.id.avi);
titleView = (TextView) findViewById(R.id.titleView);
subTitleView = (TextView) findViewById(R.id.subTitle);
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
toolbarImageView = (ImageView) findViewById(R.id.restoIcon_toolbar);
appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
priceCounterView = (TextView) findViewById(R.id.items_price_counter);
itemsCounterView = (TextView) findViewById(R.id.items_counter);
cartButton = (LinearLayout) findViewById(R.id.view_order_button);
if (cartCount == 0 && priceCount == 0){
cartButton.setVisibility(View.GONE);
}
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
tabsPager.setCurrentItem(0);
restaurant = (Restaurant) getIntent().getSerializableExtra("restaurant");
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.totalTransparent));
getSupportActionBar().setTitle(restaurant.getName());
titleView.setText(restaurant.getName());
subTitleView.setText(restaurant.getSlogan());
ratingBar.setRating(Float.parseFloat(restaurant.getRating()));
Picasso.with(context)
.load(restaurant.getImageURL())
.placeholder(R.drawable.restaurant_placeholder)
.into(toolbarImageView);
loadMenuTypes();
}
//LOAD MENU TYPES
public void loadMenuTypes(){
RequestQueue queue = Volley.newRequestQueue(this);
String url = getResources().getString(R.string.api) + "get-menu-types";
final StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("menu_types");
for (int i = 0; i < array.length(); i++){
JSONObject restoMainMenu = array.getJSONObject(i);
if (restoMainMenu.getBoolean("hasData")) {
MenuType menuType = new MenuType();
menuType.setMenuIcon(restoMainMenu.getString("icon"));
menuType.setRestaurant(restaurant);
menuType.setRmenu(restoMainMenu.getString("title"));
menuType.setMenuId(restoMainMenu.getString("id"));
menuTypes.add(menuType);
}
}
} catch (JSONException e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
loadMenuItems();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
menuTypes.clear();
menuItems.clear();
loadMenuTypes();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("UID", restaurant.getId());
return params;
}
};
queue.add(postRequest);
}
//LOAD MENUS
public void loadAllMenu(final MenuType mMenuType){
RequestQueue queue = Volley.newRequestQueue(this);
String url = getResources().getString(R.string.api) + "get-all-menu";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("detailed_menus");
List<MenuItem> menuItems1 = new ArrayList<>();
for (int i = 0; i< array.length(); i++){
JSONObject restoDetailMenu = array.getJSONObject(i);
MenuItem item = new MenuItem(
restaurant.getId(),
restoDetailMenu.getString("Name"),
restoDetailMenu.getString("id"),
restoDetailMenu.getString("Price"),
restoDetailMenu.getString("Description"),
restoDetailMenu.getString("AvailableIn"),
restoDetailMenu.getString("Icon")
);
menuItems.add(item);
menuItems1.add(item);
}
mMenuType.setMenuItems(menuItems1);
}
catch (JSONException e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
loadAllMenu(menuTypes.get(i));
Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("MenuTypeId", mMenuType.getMenuId());
params.put("restId", mMenuType.getRestaurant().getId());
return params;
}
};
queue.add(postRequest);
}
//TRIGER ALL MENU LOADER
public void loadMenuItems(){
for (int j = 0; j < menuTypes.size(); j++) {
i = j;
loadAllMenu(menuTypes.get(j));
}
avi.setVisibility(View.GONE);
setUpTabs();
}
public void setUpTabs(){
for (int j = 0; j < menuTypes.size(); j++) {
tabLayout.addTab(tabLayout.newTab().setText(menuTypes.get(j).getRmenu()));
MenuFragment fragment = new MenuFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("data", menuTypes.get(j));
fragment.setArguments(bundle);
fragments.add(MenuFragment.newInstance(menuTypes.get(j)));
}
tabsAdapter = new MenuPagerAdapter(getSupportFragmentManager(), menuTypes);
tabsAdapter.notifyDataSetChanged();
tabsPager.setAdapter(tabsAdapter);
tabLayout.setupWithViewPager(tabsPager);
tabsPager.setAdapter(tabsAdapter);
}
public void addedToCart(int price){
priceCount = priceCount + price;
cartCount = cartCount + 1;
if (cartCount > 0 && priceCount > 0){
if (cartCount == 1){
itemsCounterView.setText( String.valueOf(cartCount) + " item");
} else {
itemsCounterView.setText( String.valueOf(cartCount) + " items");
}
priceCounterView.setText(String.valueOf(priceCount) + " RWF");
cartButton.setVisibility(View.VISIBLE);
} else {
cartButton.setVisibility(View.GONE);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
PagerAdapter
public class MenuPagerAdapter extends FragmentStatePagerAdapter {
private List<MenuType> menuTypes;
public MenuPagerAdapter(FragmentManager fm, List<MenuType> menuTypes) {
super(fm);
this.menuTypes = menuTypes;
}
#Override
public Fragment getItem(int position) {
return MenuFragment.newInstance(menuTypes.get(position));
}
#Override
public int getCount() {
return menuTypes.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return menuTypes.get(position).getRmenu();
}
}
Fragment
public class MenuFragment extends Fragment {
#BindView(R.id.menuRecyclerView) RecyclerView menuRecyclerView;
#BindView(R.id.avi) AVLoadingIndicatorView avi;
private MenuType menuType;
private Bundle args;
private MenuAdapter adapter;
private Context context;
private int position;
public MenuFragment() {
// Required empty public constructor
}
public static MenuFragment newInstance(MenuType mMenuType){
MenuFragment fragment = new MenuFragment();
Bundle args = new Bundle();
args.putSerializable("data", mMenuType);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
ButterKnife.bind(this, view);
context = container.getContext();
menuRecyclerView.setHasFixedSize(true);
menuRecyclerView.setLayoutManager(new LinearLayoutManager(context));
adapter = new MenuAdapter(menuType.getMenuItems(), context);
menuRecyclerView.setAdapter(adapter);
avi.setVisibility(View.GONE);
setData();
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
args = getArguments();
menuType = (MenuType) args.getSerializable("data");
}
public MenuType getMenuType() {
return menuType;
}
public void setMenuType(MenuType menuType) {
this.menuType = menuType;
}
public void setData(){
adapter = new MenuAdapter(menuType.getMenuItems(), getActivity());
menuRecyclerView.setAdapter(adapter);
avi.setVisibility(View.GONE);
}
}
As it is seen, I'm loading MenuTypes(List) first, then for each MenuType, I load all associated items (MenuItems) List too. I, then, create Tabs with respect to the number of MenuTypes, and then create instances of the MenuFragment with respect to the number of MenuItems in the list, and the for each instance of MenuFragment, I just list MenuItems for particular MenuType in a RecyclerView(which is working fine). I tried to add a static TextView in the MenuFragment, and it was shown every time, on all tabs, but the actual data I want are not shown. I also tried a temporary solution to manually set Data I want to each created fragment from the Activity in OnPageChangeListener, but it was not directly working on the first tab until I first navigate to any other tab, which made me to opt out the strategy. Any help is much appreciated. Screenshots are also included for reference.
When tabs are 2 (Screenshot)
When tabs are 2 (Screenshot)
3 tabs, at first, the tab 1 is empty (Screenshot)
3 tabs, last tab has data (Screenshot)
3 tabs, After navigating tabs, the tab 1 also got data (Screenshot)
3 tabs, tab 2 never gets data (Screenshot)
The answer is to use the newInstance() function of the Fragment, and pass everything you want initially as arguments.
In my MainActivity I have a listview with two lines of text for each row. Only the first line is written when the app is started, the second line must be written based on the things processed by an AsyncTask class. When I try to do it, the first item of the listview gets all the values AsyncTask gives, because I don't understand how to update only the second line of the listview for each item, without rewriting the whole listview.
Every textView has its own id in the xml layout file. How can I do it in the onPostExecute()?
Here's the code:
In MainActivity onCreate():
final ListView listview = (ListView) findViewById(R.id.listview);
final String[] values = new String[10];
for(int i=0;i<10;i++){
//do stuff to write the values[] elements
}
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
listview.setAdapter(adapter);
MySimpleArrayAdapter class:
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
int position=0;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.list_layout, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_layout, parent, false);
TextView firstLine = (TextView) rowView.findViewById(R.id.label);
TextView secondLine = (TextView) rowView.findViewById(R.id.sublabel);
firstLine.setText(values[position]);
secondLine.setText(""); //I prefer to write an empty string for the secondLine
return rowView;
}
}
The AsyncTask:
private class Process extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
//do stuff
}
#Override
protected void onPostExecute(String message) {
TextView secondLine = (TextView) findViewById(R.id.sublabel);
//This of course udpdates only the secondLine of the first item of listview
secondLine.setText(processedValues);
}
}
pass the TextView as a parameter to the AsyncTask as follows
private class Process extends AsyncTask<Void, Void, String> {
private WeakReference<TextView> weakTextView;
public Process(TextView textView){
weakTextView = new WeakReference<TextView>(textView);
}
#Override
protected String doInBackground(Void... params) {
//do stuff
}
#Override
protected void onPostExecute(String message) {
TextView tv = weakTextView.get();
if(tv!=null){
tv.setText(message);
}
}
}
you call this in your getView as
Process p = new Process(yourTextView);
p.execute();
//method number two
private class Process extends AsyncTask<TextView, Void, String> {
private WeakReference<TextView> weakTextView;
#Override
protected String doInBackground(TextView... params) {
if(params == null||params.length=0){
return null;
}
TextView tv = (TextView)params[0];
weakTextView = new WeakReference<TextView>(tv);
//do stuff
}
#Override
protected void onPostExecute(String message) {
TextView tv = weakTextView.get();
if(tv!=null){
tv.setText(message);
}
}
}
you call this in your getView as
Process p = new Process();
p.execute(yourTextView);
//method 3
just update the underline data object of this list adapter
and call adapter.notifyDataSetChanged();
which will call getView again
this method, in most cases, is preferable to the other 2 above, unless you are displaying images from the internet
How to intent KEY_URL data the WV activity ?
I hope I could tell I. Thank you in advance for your help.
This is my intent button
button = (Button) findViewById(R.id.haftalikizle);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), VW.class);
i.putExtra("link",(KEY_URL).toString());
startActivity(i);
}});
This my full code, but not work. ideas, thoughts, or you can edit your.
public class haftalik extends ListActivity {
static final String URL = "https://dl.dropboxusercontent.com/s/qd33n0zxcmrnsf2/haftalik.xml";
static final String KEY_ITEM = "item";
static final String KEY_ID = "id";
static final String KEY_BILGI = "bilgi";
static final String KEY_URL = "url";
static final String KEY_THUMB_URL = "thumb_url";
public WebView tarayici;
private ProgressDialog pDialog;
ConnectivityManager connectivity = null;
ListView lv;
haftalik2 adapter;
ArrayList<HashMap<String, String>> catalogList;
Button button;
//#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.haftalik_main);
if(isConn())
{
catalogList= new ArrayList<HashMap<String, String>>();
new LoadCatalog().execute();
}
else
{
Intent i = new Intent(getApplicationContext(), dene.class);
startActivity(i);
this.finish();
}
}
class LoadCatalog extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(haftalik.this);
// pDialog.setMessage("");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all song nodes <song>
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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_BILGI, parser.getValue(e, KEY_BILGI));
map.put(KEY_URL, parser.getValue(e, KEY_URL));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
catalogList.add(map);
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
lv=getListView();
adapter=new haftalik2(haftalik.this, catalogList);
lv.setAdapter(adapter);
pDialog.dismiss();
}
});
button = (Button) findViewById(R.id.haftalikizle);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), VW.class);
i.putExtra("link",(KEY_URL).toString());
startActivity(i);
}});
}
}
public boolean isConn(){
connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivity.getActiveNetworkInfo()!=null){
if(connectivity.getActiveNetworkInfo().isConnected())
return true;
}
return false;
}
}
and my adapter class
public class haftalik2 extends BaseAdapter {
String url=null;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public haftalik2(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.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.haftalik, null);
TextView bilgi = (TextView)vi.findViewById(R.id.bilgi);
//TextView url = (TextView)vi.findViewById(R.id.url);
ImageView thumb_image=(ImageView)vi.findViewById(R.id.poster);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
bilgi.setText(song.get(haftalik.KEY_BILGI));
//url.setText(song.get(haftalik.KEY_URL));
imageLoader.DisplayImage(song.get(haftalik.KEY_THUMB_URL), thumb_image);
return vi;
}
}
I am messing around creating a "slide in"(facebook style) menu for Android, this menu will be rendered as a clickable ListView using onItemClickListener. However, when i use a custom adapter for the listview it shows nothing.
The activity which runs it is my "Root activity" which means all other activities extends it. If i place the same code in another activity it can render the listview using this adapter just fine. Also, .setOnItemClickListener seems to do nothing in the root activity. Something does not get setup like it should when this view is created, any ideas? This is the code:
public class RootActivity extends Activity {
public static final String KEY_TITLE = "title";
public static final String KEY_ID = "id";
ActionBar actionBar;
ListView slideMenu;
ListMenuAdapter adapter;
ArrayList<HashMap<String, String>> menuOptions;
private String[] menuItems={"Budget","Charts","By category"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rootview);
menuOptions = new ArrayList<HashMap<String, String>>();
slideMenu = (ListView) findViewById(R.id.slideMenuList);
slideMenu.setSaveEnabled(false);
HashMap<String, String> map;
for(int i = 0 ; i<menuItems.length ; i++ ) {
map = new HashMap<String, String>();
map.put(KEY_TITLE, menuItems[i]);
map.put(KEY_ID, ""+i);
menuOptions.add(map);
}
adapter = new ListMenuAdapter(this, menuOptions);
slideMenu.setAdapter(adapter);
Log.println(9, "slidemendeb2", ""+slideMenu.getAdapter().getCount());
slideMenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Log.println(9, "Testitemclick", ""+arg0);
}
});
}}
A sample of another activity which exends RootActivity:
public class SpentMain extends RootActivity {
public static final String KEY_TITLE = "title";
public static final String KEY_ID = "id";
ArrayList<Tag> tags;
ArrayList<Integer> tagInts = new ArrayList<Integer>();
TagDataSource tagDataSource;
Button costButton;
EditText sum;
Boolean removed = false;
ActionBar actionBar;
CheckBox checkBox;
ListView list;
ListCheckboxAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rootview);
costButton = (Button) findViewById(R.id.costadd);
sum = (EditText) findViewById(R.id.editText1);
ArrayList<HashMap<String, String>> tagsList = new ArrayList<HashMap<String, String>>();
tagDataSource = new TagDataSource(this);
tagDataSource.open();
tags = tagDataSource.getAllTags();
tagDataSource.close();
HashMap<String, String> map;
for(int i = 0 ; tags.size()>i ; i++ ) {
map = new HashMap<String, String>();
map.put(KEY_TITLE, tags.get(i).getTitle().toString());
map.put(KEY_ID, tags.get(i).getId().toString());
tagsList.add(map);
}
list=(ListView)findViewById(R.id.list);
adapter = new ListCheckboxAdapter(this, tagsList);
list.setAdapter(adapter);
// Row click event
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
for(int i = 0; tagInts.size()>i; i++) {
if(tagInts.get(i)==position) {
tagInts.remove(i);
removed = true;
}
}
if(removed==false) {
tagInts.add(position+1);
}
removed = false;
for(int i=0; i<((ViewGroup)view).getChildCount(); ++i) {
View nextChild = ((ViewGroup)view).getChildAt(i);
if(nextChild.getClass()==android.widget.CheckBox.class) {
checkBox = (CheckBox) nextChild;
if(checkBox.isChecked()==true) {
checkBox.setChecked(false);
} else {
checkBox.setChecked(true);
}
}
}
}
});}
As i said, if i use this adapter to render it within SpentMain it works fine but not within RootActivity. Any help is greatly appreciated.
Ok so i managed to fix the problem, what i did was to move the code out of onCreate in RootActivity and into its on method "buildSideMenu()". I then call that method in my SpentMain.class onCreate method like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rootview);
super.buildSideMenu();
}
I noticed that if i call super.buildSideMenu() before setContentView(R.layout.rootview) it will not work. So the problem was that since super.onCreate was being run before setContentView some things had probably not been set up properly at the time my menu was being built. Hope this can help someone else!
I made a simple AsyncTask class to display data in ListView with the help of this stackoverflow question.
But the AsyncTask onPostExecute is not being called.
This is my code:
public class Start extends SherlockActivity {
// JSON Node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
// category JSONArray
JSONArray category = null;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(SampleList.THEME); //Used for theme switching in samples
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
new MyAsyncTask().execute("http://....");
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.mail)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra("categoryname", name);
System.out.println(cost);
in.putExtra("categoryid", cost);
startActivity(in);
}
});
}
public class MyAsyncTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>> > {
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
category = jParser.getJSONArrayFromUrl(params[0]);
try {
// looping through All Contacts
for(int i = 0; i < category.length(); i++){
JSONObject c = category.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return contactList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(Start.this, result , R.layout.list_item,
new String[] { TAG_NAME, TAG_ID },
new int[] { R.id.name, R.id.mail });
// selecting single ListView item
lv = (ListView) findViewById(R.id.ListView);
lv.setAdapter(adapter);
}
}
}
Eclipse:
11-25 11:40:31.896: E/AndroidRuntime(917): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.essentials/de.main.Start}
:java.lang.NullPointerException
Because,
Your ListView lv is NULL.
You forgot to define ListView lv after setContentView(R.layout.test);
You have to do something like,
lv = (ListView) findViewById(R.id.<lisview_id_from_test.xml>);
So remove lv = (ListView) findViewById(R.id.ListView); from onPostExecute()
and put it before code line new MyAsyncTask().execute("http://....");.
Reason:
Actually what happen is,
Before going to onPostExecute() of AsyncTask, The code line lv.setOnItemClickListener(new OnItemClickListener() {...} is executed and there the Object of Listview lv is NULL.