I have made a custom Adapter and populate it with the data. I have used Logcat to see whether the array i'm passing to custom Adapter class contains the data and it does.
The error i got is following. It occurs when this CategoryBlog is created. Activity is created but it does not contain list view
exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
'mainblogpost' contains the array with all the data i want to populate with.
'MainListActivityAdapter' is the Adapter Class.
'Category_Blogs' is the class where i want to set the list view.
Category_Blog.java
I don't add import statement. there is no error in it
public class Category_Blogs extends AppCompatActivity implements AbsListView.OnItemClickListener {
public static final String TAG = MainActivity.class.getSimpleName();
public final static String EXTRA_MESSAGE = "com.example.talha.appforblog.MESSAGE";
List<StackOverflowXmlParser.Entry> mainBlogPost = new ArrayList<StackOverflowXmlParser.Entry>();
private ListAdapter mAdapter;
private AbsListView mListView;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category__blogs);
//Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
//setSupportActionBar(toolbar);
Intent intent = getIntent();
String message = intent.getStringExtra(Tab2.EXTRA_MESSAGE);
String link = message.trim() + "?feed=titles";
Log.d("ye category click krne par next activity me ye link bnta hy parsing ke liye",link);
loadPage(link);
}
#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_category__blogs, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void loadPage(String link) {
Log.d(TAG, "loadpage me a gae nh");
// if((sPref.equals(ANY)) && (wifiConnected || mobileConnected)) {
new DownloadXmlTask(this).execute(link);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
private class DownloadXmlTask extends AsyncTask<String, Void, List<StackOverflowXmlParser.Entry>> {
private Context mContext;
public DownloadXmlTask(Context context) {
mContext = context;
}
#Override
protected List<StackOverflowXmlParser.Entry> doInBackground(String... urls) {
try {
return loadXmlFromNetwork(urls[0]);
} catch (Exception e) {
Log.d("test", "" + e);
}
return null;
}
#Override
protected void onPostExecute(List<StackOverflowXmlParser.Entry> results) {
if (results != null) {
try {
String title, link, image, pubDate;
Log.d("test", "onpost");
// custom array adapter
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
for (StackOverflowXmlParser.Entry result : results) {
title = result.title;
link = result.link;
image = result.image;
pubDate = result.pubDate;
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put("link", link);
blogPost.put("title", title);
blogPost.put("image", image);
blogPost.put("pubDate", pubDate);
blogPosts.add(blogPost);
}
// copying to main item List array
for (int i = 0; i < results.size(); i++) {
mainBlogPost.add(results.get(i));
}
Log.d("fff", results.get(1).pubDate);
MainListActivityAdapter mAdapter =
new MainListActivityAdapter(Category_Blogs.this, mainBlogPost);
listView.setAdapter(mAdapter);
//((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);
// Set OnItemClickListener so we can be notified on item clicks
mListView.setOnItemClickListener(Category_Blogs.this);
}
catch (Exception e){
Log.d("test", "exception: "+e);
}
}
}
private List<StackOverflowXmlParser.Entry> loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
// Instantiate the parser
StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
List<StackOverflowXmlParser.Entry> entries = null;
String title = null;
String url = null;
try {
//opening the connection and fetching
stream = downloadUrl(urlString);
entries = stackOverflowXmlParser.parse(stream);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} catch (Exception e) {
Log.d("test", "" + e);
} finally {
if (stream != null) {
stream.close();
}
}
for (StackOverflowXmlParser.Entry entry : entries) {
Log.d("aaa",entry.pubDate);
}
return entries;
}
private InputStream downloadUrl(String urlString) throws IOException {
java.net.URL url = new java.net.URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
return conn.getInputStream();
}
}
}
MainListActivityAdapter.java
public class MainListActivityAdapter extends BaseAdapter {
private Activity activity;
List<StackOverflowXmlParser.Entry> mainBlogPost = new ArrayList<StackOverflowXmlParser.Entry>();
private static LayoutInflater inflater = null;
public MainListActivityAdapter(Activity a, List<StackOverflowXmlParser.Entry> main) {
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mainBlogPost = main;
}
public int getCount() {
return mainBlogPost.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;
Log.d("test", "fetching" + position);
String tit = mainBlogPost.get(position).title;
String cate = mainBlogPost.get(position).pubDate;
String pub = mainBlogPost.get(position).pubDate;
String image_url = "http://download.androidhive.info/img/btn_fb_login.png";
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView) vi.findViewById(R.id.title); // title
TextView cat = (TextView) vi.findViewById(R.id.category); // category
ImageView image = (ImageView) vi.findViewById(R.id.list_image); // image
TextView publish = (TextView) vi.findViewById(R.id.pubDate); // publish date
// Setting all values in listview
title.setText(tit);
cat.setText(cate);
publish.setText(pub);
Glide.with(activity)
.load(image_url)
.into(image);
return vi;
}
}
Activity_category_blog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
android:layout_height="wrap_content" tools:context="com.example.talha.test_fragement.Category_Blogs"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<include layout="#layout/tool_bar" />
<FrameLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#layout/tool_bar">
<ListView android:id="#android:id/list" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/adView" android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:layout_alignParentBottom="true"
/>
<TextView android:id="#android:id/empty" android:layout_width="match_parent"
android:layout_height="match_parent" android:gravity="center"
android:layout_gravity="right|top" />
</FrameLayout>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category__blogs);
listView = (ListView) findViewById(R.id.lvID);//where lvID is id from your listview placed in activity_category__blogs layout.
You fail to initialize the listview.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category__blogs);
//Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
**listView = (ListView) findViewById(R.id.list);**
//setSupportActionBar(toolbar);
Intent intent = getIntent();
String message = intent.getStringExtra(Tab2.EXTRA_MESSAGE);
String link = message.trim() + "?feed=titles";
Log.d("ye category click krne par next activity me ye link bnta hy parsing ke liye",link);
loadPage(link);
}
Related
This question already has answers here:
getLayoutInflater() in fragment
(5 answers)
Closed 4 years ago.
I'm trying to code an app that downloads data of some events from an online MySQL database and writes it into my android app. Right now, what i'm trying to do is just testing if downloading the name of the event works, but i keep getting this error:
java.lang.NoSuchMethodError: No virtual method getLayoutInflater()Landroid/view/LayoutInflater; in class Lcom/suspicio/appfisio_business/FrammentoCorsi; or its super classes (declaration of 'com.suspicio.appfisio_business.FrammentoCorsi' appears in /data/app/com.suspicio.appfisio_business-1/split_lib_slice_8_apk.apk)
at com.suspicio.appfisio_business.FrammentoCorsi$EventoAdapter.getView(FrammentoCorsi.java:204)
which points to the line:
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
Here's my code (it's a fragment):
FrammentoCorsi.java:
public class FrammentoCorsi extends Fragment {
public static final int CODE_GET_REQUEST = 1024;
public static final int CODE_POST_REQUEST = 1025;
public FrammentoCorsi() { //Vuoto
}
boolean isUpdating = false;
View rootView;
List<Evento> eventoList;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frammento_corsi, container, false);
listView = (ListView) rootView.findViewById(R.id.listViewEventi);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
eventoList = new ArrayList<>();
readEventi();
}
private void readEventi() {
PerformNetworkRequest request = new PerformNetworkRequest(Api.URL_READ_EVENTI, null, CODE_GET_REQUEST);
request.execute();
}
private void refreshEventoList(JSONArray eventi) throws JSONException {
//clearing previous heroes
eventoList.clear();
//traversing through all the items in the json array
//the json we got from the response
for (int i = 0; i < eventi.length(); i++) {
//getting each hero object
JSONObject obj = eventi.getJSONObject(i);
//adding the hero to the list
eventoList.add(new Evento(
obj.getInt("id"),
obj.getString("titolo"),
obj.getString("inizio"),
obj.getString("fine"),
obj.getInt("categoria"),
obj.getString("link"),
obj.getString("luogo")
));
}
//creating the adapter and setting it to the listview
EventoAdapter adapter = new EventoAdapter(eventoList);
listView.setAdapter(adapter);
}
//inner class to perform network request extending an AsyncTask
public class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
//the url where we need to send the request
String url;
//the parameters
HashMap<String, String> params;
//the request code to define whether it is a GET or POST
int requestCode;
ProgressBar barra = (ProgressBar) getView().findViewById(R.id.progressBar);
//constructor to initialize values
PerformNetworkRequest(String url, HashMap<String, String> params, int requestCode) {
this.url = url;
this.params = params;
this.requestCode = requestCode;
}
//when the task started displaying a progressbar
#Override
protected void onPreExecute() {
super.onPreExecute();
barra.setVisibility(View.VISIBLE);
}
//this method will give the response from the request
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
barra.setVisibility(View.INVISIBLE);
try {
JSONObject object = new JSONObject(s);
if (!object.getBoolean("error")) {
Toast.makeText(getActivity().getApplicationContext(), object.getString("message"), Toast.LENGTH_SHORT).show();
refreshEventoList(object.getJSONArray("eventi"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//the network operation will be performed in background
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
}
}
class EventoAdapter extends ArrayAdapter<Evento> {
List<Evento> eventoList;
//constructor to get the list
public EventoAdapter(List<Evento> eventoList) {
super(getActivity(), R.layout.frammento_corsi, eventoList);
this.eventoList = eventoList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listViewItem = convertView;
if (listViewItem == null) {
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
}
//getting the textview for displaying name
TextView textViewName = listViewItem.findViewById(R.id.nomeeventocalendario);
//the update and delete textview
//ImageView textViewUpdate = listViewItem.findViewById(R.id.notifica);
//ImageView textViewDelete = listViewItem.findViewById(R.id.link);
final Evento evento = eventoList.get(position);
textViewName.setText(evento.getTitolo());
return listViewItem;
}
}
}
And its resource file frammento_corsi.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.suspicio.appfisio_business.FrammentoCorsi">
<ListView
android:id="#+id/listViewEventi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/nomeeventocalendario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone"/>
</FrameLayout>
Can you help me out?
Thanks in advance!
Use this
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
listViewItem = layoutInflater.inflate(R.layout.frammento_corsi, null ,true);
Instead of this
listViewItem = getLayoutInflater().inflate(R.layout.frammento_corsi, null, true);
I need some help with the logic to my problem. I have searched already on here for posts discussing similar issues, however haven't yet had success in fixing my problem so I don't wish to make this a duplicate post.
I am working on an app and I am having issues in displaying parsed JSON Data in a recycler view within a Slide Tab Fragment. I have a Sliding Tabs on my main activity with five fragments in total, one for each tab (5 tabs in total). What I want to do for the third tab is to display a recycler view with parsed JSON data that is being retrieved from the server. I have the same functionality within an activity for my other recyclerviews and they work fine. I was just struggling slightly on how to achieve this inside a fragment. I am providing the below code for troubleshooting and debugging purposes:
Here is the code to my MainActivity.java
public class MainActivity extends BaseActivity {
private ViewPager mPager;
private SlidingTabLayout mTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// To track statistics around application
ParseAnalytics.trackAppOpened(getIntent());
// inform the Parse Cloud that it is ready for notifications
ParseInstallation.getCurrentInstallation().saveInBackground();
//Calling Activate Toolbar method
activateToolBar();
mPager = (ViewPager) findViewById(R.id.pager);
//Setting the Adapter on the view pager first. Passing the fragment manager through as an argument
mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
//Setting the custom Tab View as the Sliding Tabs Layout
mTabs.setCustomTabView(R.layout.custom_tab_view, R.id.tabText);
mTabs.setDistributeEvenly(true);
//mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.tabIndicatorColour));
mTabs.setBackgroundColor(getResources().getColor(R.color.basePrimaryBackgroundColour));
//Setting the ViewPager as the tabs
mTabs.setViewPager(mPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//int id = item.getItemId();
//noinspection SimplifiableIfStatement
//if (id == R.id.action_settings) {
// return true;
//}
return super.onOptionsItemSelected(item);
}
class MyPagerAdapter extends FragmentPagerAdapter {
String[] tabs;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
//Initialising the strings array of the tabs
tabs = getResources().getStringArray(R.array.tabs);
}
/*
//Setting up integer array of icons
int icons[] = {R.drawable.about_us, R.drawable.campus, R.drawable.events, R.drawable.learning, R.drawable.sewa};
//Defined from strings.xml
String[] tabText = getResources().getStringArray(R.array.tabs);
public MyPagerAdapter(FragmentManager fm) {
super(fm);
//Initialising the strings array of tabs
tabText = getResources().getStringArray(R.array.tabs);
}
*/
#Override
public Fragment getItem(int position) {
if (position == 0) // if the position is 0 we are returning the First tab
{
Tab1 tab1 = new Tab1();
return tab1;
} else if (position == 1)
{
Tab2 tab2 = new Tab2();
return tab2;
} else if (position == 2)
{
Tab3 tab3 = new Tab3();
return tab3;
} else if (position == 3)
{
Tab4 tab4 = new Tab4();
return tab4;
} else
{
Tab5 tab5 = new Tab5();
return tab5;
}
}
#Override
public CharSequence getPageTitle(int position) {
//Return the text of the position clicked and display this as the title for the tab
return tabs[position];
}
#Override
public int getCount() {
return 5;
}
}
}
This is the code for my RecyclerViewAdapterEvents.java
public class RecyclerViewAdapterEvents extends RecyclerView.Adapter<RecyclerViewAdapterEvents.MyViewHolder> {
private LayoutInflater inflater;
//private EventsActivity activity;
private List<JSONEventsItem> data = Collections.emptyList();
private Context mContext;
//Variable for the on click Listener
private ClickListener clickListener;
//Passing in the array list argument
public RecyclerViewAdapterEvents(Context context, List<JSONEventsItem> data) {
this.mContext = context;
//this.activity = activity;
inflater = LayoutInflater.from(context);
//Setting the array list data to the argument passed in
this.data = data;
}
#Override
public RecyclerViewAdapterEvents.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Inflating the row and getting the root of view of the custom row (Linear Layout)
View view = inflater.inflate(R.layout.custom_row, parent, false);
//Passing the root view through as an argument
MyViewHolder holder = new MyViewHolder(view);
//Returning the view holder
return holder;
}
#Override
public void onBindViewHolder(RecyclerViewAdapterEvents.MyViewHolder holder, int position) {
//This will get the current position of the JSONEventItem object from the array
JSONEventsItem eventsItem = data.get(position);
//Setting the event name to the name of the event retrieved from the Database (converting from JSON)
holder.eventName.setText(Html.fromHtml(eventsItem.getEventName()));
}
#Override
public int getItemCount() {
return (null != data ? data.size() : 0);
}
public void setClickListener(ClickListener clicklistener) {
this.clickListener = clicklistener;
}
public interface ClickListener {
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView eventName;
public MyViewHolder(View itemView) {
super(itemView);
//Here setting the id of the textview in the recycler view holder to be the list view from the custom_row xml
eventName = (TextView) itemView.
findViewById(R.id.listText);
}
}
}
Here is the class file for Tab3 Fragment, Tab3.java
public class Tab3 extends Fragment implements RecyclerViewAdapterEvents.ClickListener{
private RecyclerView mRecyclerView;
//Creating an instance of the adapter object
private RecyclerViewAdapterEvents adapter;
private List<JSONEventsItem> EventsList;
private String jsonString = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.tab_3,container,false);
//Instantiating the recycler view as defined in tab_1
mRecyclerView = (RecyclerView) v.findViewById(R.id.about_us_recycler_view);
//Adding item decoration. Recycler view divider
mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
//Initialising the adapter - Passing in the activity and the getData method
adapter = new RecyclerViewAdapterEvents(getActivity(), EventsList);
//Here passing in the click listener into the Adapter. 'this' signifies that it is the fragment that handles the click listener.
//This is possible as the on Click Listener interface is being implemented.
adapter.setClickListener(this);
//Setting the adapter
mRecyclerView.setAdapter(adapter);
//Setting the Layout
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//Downloading data from below url (Universal Resource Locator) to obtain data from the Admin database
final String url = "http://dbchudasama.webfactional.com/jsonscript.php";
new AsyncHTTPTask().execute(url);
return v;
}
public class AsyncHTTPTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
jsonString = response.toString();
parseResult();
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d("Exception Caught", e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
//adapter.getItemCount();
if (result == 1) {
//Intent intent = getIntent();
//intent.getSerializableExtra("JSON Admin");
//Initialising the adapter - Passing in the activity and the parsed Admin Team List
adapter = new RecyclerViewAdapterEvents(getActivity(), EventsList);
//Setting the adapter
mRecyclerView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
}
}
//This method will parse the RAW data downloaded from the server
private void parseResult() {
try {
JSONArray AdminArrays = new JSONArray(jsonString);
EventsList = new ArrayList<>();
for (int i = 0; i < AdminArrays.length(); i++) {
JSONObject AdminArrayObject = AdminArrays.getJSONObject(i);
JSONEventsItem item = new JSONEventsItem();
item.setEventName(AdminArrayObject.getString("eventName"));
this.EventsList.add(item);
Log.e("Event Name", AdminArrayObject.getString("eventName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The Tab3.java code has crashed all my other tabs and is giving a null pointer exception on the the getActivity() method, as this is being performed on a null object reference. Could I just declare an activity of type EventsActivity and pass this through instead? Also So I am slightly unsure how to resolve this. For completeness I have also written the same code within an activity EventsActivity.java which I know will work. It is just getting it to run within the fragment.
public class EventsActivity extends BaseActivity implements RecyclerViewAdapterEvents.ClickListener {
private RecyclerView mRecyclerView;
//Creating an instance of the adapter object
private RecyclerViewAdapterEvents adapter;
private List<JSONEventsItem> EventsList;
private EventsActivity activity;
private String jsonString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_3);
//Calling Activate Toolbar method (with the Back button enabled)
activateToolbarWithHomeEnabled();
//Instantiating the recycler view as defined in admin_team
//mRecyclerView = (RecyclerView) findViewById(R.id.events_recycler_view);
//Adding item decoration. Recycler view divider
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
//Initialising the adapter - Passing in the activity and the parsed Events List
adapter = new RecyclerViewAdapterEvents(this, EventsList);
//Setting the adapter
mRecyclerView.setAdapter(adapter);
//Setting the Layout
//mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//Downloading data from below url (Universal Resource Locator) to obtain data from the Admin database
final String url = "http://dbchudasama.webfactional.com/jsonscript.php";
new AsyncHTTPTask().execute(url);
}
public class AsyncHTTPTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
jsonString = response.toString();
parseResult();
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d("Exception Caught", e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
//adapter.getItemCount();
if (result == 1) {
//Intent intent = getIntent();
//intent.getSerializableExtra("JSON Admin");
//Initialising the adapter - Passing in the activity and the parsed Admin Team List
adapter = new RecyclerViewAdapterEvents(EventsActivity.this, EventsList);
//Setting the adapter
mRecyclerView.setAdapter(adapter);
} else {
Toast.makeText(EventsActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
}
}
//This method will parse the RAW data downloaded from the server
private void parseResult() {
try {
JSONArray AdminArrays = new JSONArray(jsonString);
EventsList = new ArrayList<>();
for (int i = 0; i < AdminArrays.length(); i++) {
JSONObject AdminArrayObject = AdminArrays.getJSONObject(i);
JSONEventsItem item = new JSONEventsItem();
item.setEventName(AdminArrayObject.getString("eventName"));
this.EventsList.add(item);
Log.e("Event Name", AdminArrayObject.getString("eventName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is my crash log from Logcat:
11-09 18:56:21.587 2961-2961/com.divyeshbc.NHSF E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.divyeshbc.NHSF, PID: 2961
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.addItemDecoration(android.support.v7.widget.RecyclerView$ItemDecoration)' on a null object reference
at com.divyeshbc.NHSF.tabs.events.Tab3.onCreateView(Tab3.java:53)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:551)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:513)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:494)
at com.divyeshbc.NHSF.tabs.SlidingTabLayout$TabClickListener.onClick(SlidingTabLayout.java:324)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Where am I going wrong? Any guidance will be highly helpful :).
Thanks
i have a problem with handling screen rotation and AsyncTask in my activity.
Here's the problem:
I have a MainActivity which has inside a PostersFragment, who manages the layout. Inside it there is a GridView to populate with some images fetched by an AsyncTask.
When i rotate the device it messess up, and i can see an old GridView behind the actual GridView.
It surely is a problem bound to recreation of the activity, i googled a lot and found the setRetainInstance(true) method, i tried to call it in my fragment but nothing changed.
Here's the MainActivity code:
public class MainActivity extends ActionBarActivity {
private final String POSTERSFRAGMENT_TAG ="PFTG";
private DrawerLayout mDrawer;
private ListView mDrawerListView;
private Toolbar toolbar;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().add(R.id.frame_container, new PostersFragment(), POSTERSFRAGMENT_TAG).commit();
String[] drawerChoices = getResources().getStringArray(R.array.drawer_choices_array);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerListView = (ListView) findViewById(R.id.left_drawer);
mDrawerListView.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, drawerChoices));
mDrawerListView.setOnItemClickListener(new DrawerItemClickListener());
toolbar = (Toolbar) findViewById(R.id.main_activity_toolbar);
if(toolbar!=null){
toolbar.setTitle(getResources().getString(R.string.app_name));
setSupportActionBar(toolbar);
}
mDrawerToggle = new ActionBarDrawerToggle(this,mDrawer,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawer.setDrawerListener(mDrawerToggle);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String x =parent.getItemAtPosition(position).toString();
if(x.equals(getString(R.string.trending_drawer_option))) {
PostersFragment fragment = new PostersFragment();
getFragmentManager().beginTransaction().replace(R.id.frame_container, fragment).commit();
mDrawer.closeDrawer(mDrawerListView);
}
if(x.equals(getString(R.string.bookmarked_drawer_option))){
BookmarksFragment fragment = new BookmarksFragment();
getFragmentManager().beginTransaction().replace(R.id.frame_container,fragment).commit();
mDrawer.closeDrawer(mDrawerListView);
}
if(x.equals(getString(R.string.settings_drawer_option))){
mDrawer.closeDrawer(mDrawerListView);
Intent intent = new Intent(getApplicationContext(),SettingsActivity.class);
startActivity(intent);
}
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawer.isDrawerOpen(mDrawerListView);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mDrawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
}
And the PostersFragment code:
public class PostersFragment extends android.app.Fragment {
public static final int MAX_PAGES = 50;
public int mPagesLoaded = 0;
private ImageAdapter mImages;
public boolean mIsLoading = false;
public TextView loadingText;
private SharedPreferences sharedPrefs;
private SharedPreferences.OnSharedPreferenceChangeListener spChanged;
public PostersFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mImages = new ImageAdapter(getActivity());
View view = inflater.inflate(R.layout.fragment_main,container,false);
loadingText = (TextView) view.findViewById(R.id.loadingTextView);
loadingText.setVisibility(View.GONE);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
spChanged = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
mImages.clear();
mPagesLoaded=0;
}
};
sharedPrefs.registerOnSharedPreferenceChangeListener(spChanged);
initGrid(view);
startLoading();
return view;
}
private void startLoading()
{
if(mPagesLoaded>=MAX_PAGES)
return;
if(mIsLoading==true)
return;
mIsLoading=true;
if(loadingText!=null)
loadingText.setVisibility(View.VISIBLE);
new FetchPageTask().execute(mPagesLoaded + 1);
}
private void stopLoading()
{
if(mIsLoading==false)
return;
if(mIsLoading==true)
mIsLoading=false;
if(loadingText!=null)
loadingText.setVisibility(View.GONE);
}
private void initGrid(View view)
{
GridView gridView = (GridView) view.findViewById(R.id.gridView);
if(gridView==null)
return;
gridView.setAdapter(mImages);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageAdapter adapter = (ImageAdapter) parent.getAdapter();
Movie movie = adapter.getItem(position);
if (movie == null)
return;
//intent to be launched
Intent intent = new Intent(getActivity(),DetailActivity.class);
intent.putExtra(Movie.EXTRA_MOVIE,movie.toBundle());
getActivity().startActivity(intent);
}
});
gridView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastScreen = firstVisibleItem + visibleItemCount;
if(lastScreen == totalItemCount)
startLoading();
}
});
}
private class FetchPageTask extends AsyncTask<Integer,Void,Collection<Movie>> {
public final String LOG_TAG = FetchPageTask.class.getSimpleName();
#Override
protected Collection<Movie> doInBackground(Integer... params) {
if (params.length == 0)
return null;
int page = params[0];
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String responseJsonStr = null;
try {
final String API_BASE_URL = "http://api.themoviedb.org/3/movie/";
final String API_PARAM_PAGE = "page";
final String API_PARAM_KEY = "api_key";
final String API_SORTING = sharedPrefs.getString(getString(R.string.pref_sorting_key),getString(R.string.pref_sorting_default_value));
Uri builtUri = Uri.parse(API_BASE_URL).buildUpon()
.appendPath(API_SORTING)
.appendQueryParameter(API_PARAM_PAGE, String.valueOf(page))
.appendQueryParameter(API_PARAM_KEY, getString(R.string.my_api_key))
.build();
Log.d(LOG_TAG, "Query URI: " + builtUri.toString());
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
buffer.append(line + "\n");
if (buffer.length() == 0)
return null;
responseJsonStr = buffer.toString();
} catch (Exception e) {
Log.e(LOG_TAG, "Error", e);
return null;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing input stream", e);
}
}
}
try {
return fetchMoviesFromJson(responseJsonStr);
} catch (JSONException je) {
Log.d(LOG_TAG, "Can't parse JSON " + responseJsonStr, je);
return null;
}
}
private Collection<Movie> fetchMoviesFromJson(String jsonStr) throws JSONException {
final String KEY_MOVIES = "results";
JSONObject json = new JSONObject(jsonStr);
JSONArray movies = json.getJSONArray(KEY_MOVIES);
ArrayList<Movie> result = new ArrayList<Movie>();
for (int i = 0; i < movies.length(); i++) {
result.add(Movie.getMovieFromJson(movies.getJSONObject(i)));
}
return result;
}
#Override
protected void onPostExecute(Collection<Movie> movies)
{
stopLoading();
mPagesLoaded++;
mImages.addAll(movies);
}
}
}
How can I prevent it from duplicating? How should i handle the change of configuration?
In your onCreate for MainActivity replace this line:
getFragmentManager().beginTransaction().add(R.id.frame_container, new PostersFragment(), POSTERSFRAGMENT_TAG).commit();
to
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.frame_container, new PostersFragment(), POSTERSFRAGMENT_TAG).commit();
}
EDIT: Sorry, I didn't clarify as to why this is required. The purpose of this check is to see if the fragment is already there. When can we confirm that the fragment is not there? When savedInstanceState is null.
Initially, the Bundle is null when the activity is first created. When the device has a configuration change, all activities/fragments are destroyed and recreated, excepting the ones on which setRetainInstance(true) has been called. These fragments are not destroyed. They are just attached to the new activity…
When the activity is recreated after the configuration change, the instance of the retained fragment is already present, and the savedInstanceState is not null as a result of this. Hence, you check if savedInstanceState == null and only then proceed to add the fragment to avoid duplicated.
I know there are a lot of posts on how to make an Android ListView, but even after looking through most of them I can't figure out what my problem is. I'm completely new to Android and obviously a bit overwhelmed. The activity runs but without showing any content.
This is my Activity:
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
public class HistoryActivity extends Activity {
CustomRowAdapter customRowAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
listView = (ListView)findViewById(R.id.listView);
customRowAdapter = new CustomRowAdapter(getApplicationContext());
listView.setAdapter(customRowAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.history, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is activity_history.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
The xml for the input in the ListView (custom_row.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/textView1"
android:background="#drawable/box"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name" />
<TextView
android:id="#+id/textView2"
android:background="#drawable/box"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name" />
<TextView
android:id="#+id/textView3"
android:background="#drawable/box"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name" />
</LinearLayout>
and CustomRowAdapter.java:
package com.example.myfirstapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomRowAdapter extends ArrayAdapter<String> {
private String[] text1 = {
"Google Plus",
"Twitter",
"Facebook",
"Instagram"};
private String[] text2 = {
"test1",
"test2",
"test3",
"test4"};
private String[] text3 = {
"Google Plus",
"Twitter",
"Facebook",
"Instagram"};
private LayoutInflater layoutInflater;
private Context context;
public CustomRowAdapter(Context context) {
super(context,0);
layoutInflater= (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context=context;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup){
view = layoutInflater.inflate(R.layout.custom_row,null);
TextView textViewT1 = (TextView)view.findViewById(R.id.textView1);
TextView textViewT2 = (TextView)view.findViewById(R.id.textView2);
TextView textViewT3 = (TextView)view.findViewById(R.id.textView3);
// textViewT1.setText("test");
// textViewT2.setText(text2[0]);
// textViewT3.setText(text3[0]);
return view;
}
#Override
public int getCount(){
return 0;
}
}
Hope somebody can help me out.
Your ListView is not showing nothing because of
#Override
public int getCount(){
return 0;
}
getCount has to return the number of elements that belong to your dataset. For instance
#Override
public int getCount(){
return text1.length;
}
You're returning 0 from getCount. Return the number of items in the list here, I suspect you want something like text1.length.
Hey i see my simple and best example, Follow some steps
I mostly use custom for testing
JSON Parsing
Step 1.
JSONParser.java
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("response", "" + httpResponse);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
Sept 2.
MainHome.java
public class MainActivity extends Activity {
ListView lvdata;
LinkedList<HashMap<String, String>> aldata = new LinkedList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
new getData().execute();
}
void init() {
lvdata = (ListView) findViewById(R.id.lvdata);
}
private class getData extends AsyncTask<Void, Void, String> {
Dialog dialog;
String url;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
url = "Enter your url";
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
try {
JSONObject jobject = new JSONObject(json);
int success = jobject.getInt("success");
for (int i = 0; i < jobject.length() - 1; i++) {
JSONObject jobj = jobject
.getJSONObject(Integer.toString(i));
if (success == 1) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("p_name", jobj.getString("p_name"));
hm.put("p_title", jobj.getString("p_title"));
aldata.add(hm);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null)
if (dialog.isShowing())
dialog.dismiss();
Custom_Adapter adapter = new Custom_Adapter(
(Activity) MainActivity.this, aldata);
lvdata.setAdapter(adapter);
}
}
}
Custom Adapter
Custom_Adapter.java
public class Custom_Adapter extends ArrayAdapter<HashMap<String, String>> {
private final Activity context;
private final LinkedList<HashMap<String, String>> allData;
public Custom_Adapter(Activity context,
LinkedList<HashMap<String, String>> list) {
super(context, R.layout.custom_list, list);
this.context = context;
this.allData = list;
}
static class ViewHolder {
TextView tvname, tvinfo;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
view = null;
if (view == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.custom_list, null);
final ViewHolder viewHolder = new ViewHolder();
initAll(view, viewHolder);
view.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) view.getTag();
fillAll(holder, position);
return view;
}
public void initAll(View view, ViewHolder viewHolder) {
viewHolder.tvname = (TextView) view.findViewById(R.id.tvname);
viewHolder.tvinfo = (TextView) view.findViewById(R.id.tvinfo);
}
public void fillAll(final ViewHolder holder, final int position) {
holder.tvname.setText(allData.get(position).get("p_name"));
holder.tvinfo.setText(allData.get(position).get("p_title"));
}
}
What i have done::I have got s list of items from server & display in listview
each row of list has a checkbox in it, list view also has a button on top as show in figure below
What i need to do ::
out of six rows if i select three rows using checkbox on click of
button next showed in figure i must be able to display the toast
message of selected elements
I don't know how to fill the parts of onclick function of
checkButtonClick() in code
ListViewAdapterForAtomicListItemtype.java
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
// Capture position and set results to the TextViews
name.setText(resultp.get(MainActivity.NAME));
return itemView;
}
}
listview_main_atomic_list_itemtype.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/button1" />
<Button
android:id="#+id/button_of_listview_main_atomic_list_itemtype_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="DisplayItems" />
</RelativeLayout>
listview_item_for_atomic_list_item_type.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView_id_atomic_list_item_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/checkBox_atomic_list_item_type_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
</RelativeLayout>
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
String TYPE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main_atomic_list_itemtype);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
{EDIT}
BLD_IndividualListOfItems_Starters.java
public class BLD_IndividualListOfItems_Starters extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapterForAtomicListItemtype adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
String TYPE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main_atomic_list_itemtype);
TYPE_FILTER = getIntent().getExtras().getString("key_title");
Log.v("---- Value-Start---", TYPE_FILTER);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(BLD_IndividualListOfItems_Starters.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String newurl = "?" + "Key=" + TYPE_FILTER;
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("http://54.218.73.244:7005/RestaurantAtomicListItemType/"+newurl);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("MasterListMenuName"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapterForAtomicListItemtype(BLD_IndividualListOfItems_Starters.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.button_of_listview_main_atomic_list_itemtype_id);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<arraylist.size();i++)
{
if(adapter.mCheckStates.get(i)==true)
{
result.append(arraylist.get(i).get(MainActivity.NAME));
result.append("\n");
}
}
Toast.makeText(BLD_IndividualListOfItems_Starters.this, result, 1000).show();
}
});
}
}
ListViewAdapterForAtomicListItemtype.java
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements android.widget.CompoundButton.OnCheckedChangeListener{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
SparseBooleanArray mCheckStates;
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
mCheckStates = new SparseBooleanArray(data.size());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item_for_atomic_list_item_type, parent, false);
// Get the position
CheckBox chkSelect =(CheckBox) itemView.findViewById(R.id.checkBox_atomic_list_item_type_id);
chkSelect.setTag(position);
chkSelect.setChecked(mCheckStates.get(position, false));
chkSelect.setOnCheckedChangeListener(this);
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView_id_atomic_list_item_type);
// Capture position and set results to the TextViews
name.setText(resultp.get(MainActivity.NAME));
return itemView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
you can also use for MULTIPLE CHOICE OF LISTVIEW.
StringBuilder result;
After Click on Button you can do this:
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
result = new StringBuilder();
for (int i = 0; i < arraylist.size(); i++) {
if (adapter.mysparse.get(i) == true) {
result.append(arraylist.get(i).get(MainActivity.NAME));
result.append("\n");
}
}
Intent n = new Intent(MainActivity.this, DisplayActivity.class);
n.putExtra("buffer", result.toString());
startActivity(n);
}
});
And in your DisplayActivity you can do like this:
package com.example.singleitemlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DisplayActivity extends Activity {
ListView lv;
ArrayList<String> myList;
String myName;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent n = getIntent();
myName = n.getStringExtra("buffer");
myList = new ArrayList<String>();
lv = (ListView) findViewById(R.id.listViewData);
myList.add(myName);
lv.setAdapter(new ArrayAdapter<String>(DisplayActivity.this,
android.R.layout.simple_list_item_1, myList));
}
}
Use a SparseBooleanArray.
More info #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
In your adapter implement CompoundButton.OnCheckedChangeListener
public class ListViewAdapterForAtomicListItemtype extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{
SparseBooleanArray mCheckStates;
public ListViewAdapterForAtomicListItemtype(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
mCheckStates = new SparseBooleanArray(data.size());
}
Then in getView
CheckBox chkSelect =(CheckBox) item.findViewById(R.id.CheckBox
android:id="#+id/checkBox_atomic_list_item_type_id");
chkSelect.setTag(position);
chkSelect.setChecked(mCheckStates.get(position, false));
chkSelect.setOnCheckedChangeListener(this);
Override the following methods
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
In onClick of Button
StringBuilder result = new StringBuilder();
for(int i=0;i<arraylist.size();i++)
{
if(adapter.mCheckStates.get(i)==true)
{
result.append(arrayList.get(i).get(MainActivtiy.Name));
result.append("\n");
}
}
Toast.makeText(ActivityName.this, result, 1000).show();
Note:
It is better to use a ViewHolder Pattern.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
StringBuffer result = new StringBuffer();
result.append("TEXTVIEW 1 : ").append(chkbox1.isChecked());
result.append("\nTEXTVIEW 2 : ").append(chkbox2.isChecked());
result.append("\nTEXTVIEW 3 :").append(chkbox3.isChecked());
//and so on.........
Toast.makeText(MyAndroidAppActivity.this, result.toString(),
Toast.LENGTH_LONG).show();
I think this wat you need. Just update you got solution or not. this code must be in the next button onclickListener.
Try it out nd vote and ping if works. before tat update wats happening.
ADDED:
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String ss;
ss=(String) ((TextView) view).getText();
This code is to check which item is clicked.
by this with lenght of the list , check in for loop to check whether its checkbox is clicked or not.
Aftert that you can easily append that list of checked items.
Never tried but should work..you can use following code inside onClick() to get CheckBox status for each row.
if (adapter!=null&&adapter.getCount()>0) {
for(int i=0;i<adapter.getCount();i++){
View view=(View)adapter.getItem(i);
CheckBox chk=(CheckBox)view.findViewById(R.id.checkbox);
TextView txt=(TextView)view.findViewById(R.id.textview);
if (chk.isChecked()) {
//do something here
}
}
}