Hi guys I am implementing a listview with a clickable button through this tutorial -> https://www.youtube.com/watch?v=ZEEYYvVwJGY
and I want to achieve the same output.
But I have a slight problem, since my list view is populated from mysql database but in the tutorial is not populated from mysql database so we have a different adapter.
Codes in the tutorial
public class MainActivity extends AppCompatActivity{
private ArrayList<String> data = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
ListView lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new MyListAdapter(this, R.layout.list_item, data));
}
}
Then lets assume that this is the tutorials MyListAdapter
private class MyListAdapter extends ArrayAdapter<String>{
private int layout;
public MyListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewHolder = null;
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
return convertView;
}
}
and my problem is in this part
the setAdapter
mylistView = (ListView) findViewById(R.id.list);
final ListAdapter adapter = new SimpleAdapter(Attendance.this,
studentList, R.layout.list_att, new String[]{
TAG_ID, TAG_NAME}, new int[]{
R.id.studId, R.id.studName});
mylistView.setAdapter(adapter);
what should I do? any help would be appreciated thanks in advance :)
this is my code
public class Attendance extends AppCompatActivity {
TextView Date;;
ListView mylistView;
private ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
TextView Name;
private static String url = "http://10.0.2.2/MobileClassRecord/getStudent.php";
private static final String TAG_STUDENTS = "students";
private static final String TAG_ID = "stud_id";
private static final String TAG_NAME = "stud_name";
JSONArray students = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Date = (TextView) findViewById(R.id.tvDate);
final Calendar calendar = Calendar.getInstance();
int dd = calendar.get(Calendar.DAY_OF_MONTH);
int mm = calendar.get(Calendar.MONTH);
int yy = calendar.get(Calendar.YEAR);
Date.setText(new StringBuilder().append(yy).append("-").append(mm + 1).append("-").append(dd));
new JSONParse().execute();
studentList = new ArrayList<HashMap<String, String>>();
}
private class JSONParse extends AsyncTask<String, String, JSONObject>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Name =(TextView) findViewById(R.id.studName);
pDialog = new ProgressDialog(Attendance.this);
pDialog.setMessage("Getting Data from Database...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
pDialog.dismiss();
try {
students = jsonObject.getJSONArray(TAG_STUDENTS);
for (int i = 0; i < students.length(); i++){
JSONObject c =students.getJSONObject(i);
final String Id = c.getString(TAG_ID);
String Name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, Id);
map.put(TAG_NAME, Name);
studentList.add(map);
mylistView = (ListView) findViewById(R.id.list);
final ListAdapter adapter = new SimpleAdapter(Attendance.this,
studentList, R.layout.list_att, new String[]{
TAG_ID, TAG_NAME}, new int[]{
R.id.studId, R.id.studName});
mylistView.setAdapter(adapter);
mylistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String ID = ((TextView) (view.findViewById(R.id.studId))).getText().toString();
Toast.makeText(Attendance.this, "List Clicked " + ID, Toast.LENGTH_LONG).show();
SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
preferences.edit().putString("id", ID).commit();
}
});
}
}catch (JSONException e){
e.printStackTrace();
}
}
}
private class MyListAdapter extends ArrayAdapter<String>{
private int layout;
public MyListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewHolder = null;
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
mainViewHolder = (ViewHolder) convertView.getTag();
mainViewHolder.tvid.setText(getItem(position));
return convertView;
}
}
public class ViewHolder{
TextView tvid, tvname;
Button btnP, btnA;
}
#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_attendance, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Intent intent = new Intent(Attendance.this, SpecificClassRecord.class);
startActivity(intent);
return true;
case R.id.action_view_attendance:
Intent intent1 = new Intent(Attendance.this, ViewAttendance.class);
startActivity(intent1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Sample Layout
like Udi said, more information would be nice.
One strange thing in your code is in the getView() method.
you have
if(convertView==null){
...
}else{
...
}
I think the else part is wrong. Just remove the else and the brackets (not the code insight of it).
The code in the else part is important, because without it the code will not change the TextView when the View is loaded for the first time. This mean, that your getView will do nothing
EDIT
The author has changed the code. You have now two different adapters there...
In my opinion the getView() Method should look like this
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewHolder = null;
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
mainViewHolder = (ViewHolder) convertView.getTag();
mainViewHolder.tvid.setText(getItem(position));
return convertView;
}
}
But for me it is still not clear where exactly the problem is. Is the App crashing or is there just a behavior you don't understand? If yes, what exactly?
If the App is crashing, when exactly?
EDIT 2:
mylistView = (ListView) findViewById(R.id.list);
final ListAdapter adapter = new MyListAdapter(Attendance.this,
R.layout.list_att, new String[]{
TAG_ID, TAG_NAME});
mylistView.setAdapter(adapter);
maybe this is all. I assume the layout of your rows is given by the layoutressource R.layout.list_att and that TAG_ID and TAG_Name are defined somewhere before.
I see your new Adapter needs a List of Strings. Insert the following before you set the adapter
List<String> test = new ArrayList<String>();
test.add("1");
test.add("2"):
test.add("3");
and then your adapter should look like this
final ListAdapter adapter = new MyListAdapter(Attendance.this,
R.layout.list_att, test);
Related
I'm trying to show json data in listview in android. I'm getting json data perfectly but when i'm trying to show it in listview just getting only one row.
And i want to show data of each row in an activity as per item click. Here i'm not understanding how to pass the data from json depending on which item is clicked.
here is my code:
public class CustomAdapter extends ArrayAdapter {
List list = new ArrayList();
public CustomAdapter(Context context, int resource) {
super(context, resource);
}
public void add(DataProvider dataProvider) {
super.add(dataProvider);
list.add(dataProvider);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row = convertView;
dataProviderHolder holder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_list, parent, false);
holder = new dataProviderHolder();
holder.name = (TextView) row.findViewById(R.id.name);
holder.subject = (TextView) row.findViewById(R.id.subject);
holder.date = (TextView) row.findViewById(R.id.date);
holder.time = (TextView) row.findViewById(R.id.tim);
row.setTag(holder);
} else {
holder = (dataProviderHolder) row.getTag();
}
DataProvider provider = (DataProvider) this.getItem(position);
holder.name.setText(provider.getName());
holder.subject.setText(provider.getSubject());
holder.date.setText(provider.getDate());
holder.time.setText(provider.getTime());
return row;
}
static class dataProviderHolder {
TextView name, subject, date, time;
}
}
Json parsing :
listView = (ListView) findViewById(R.id.list);
sessionManager = new SessionManager(this);
listView.setAdapter(customAdapter);
HashMap<String, String> user = sessionManager.getUserDetails();
json_string = user.get(SessionManager.JSON_STRING);
try {
String name, subject, message, date, time;
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("message");
int count = 0;
while (count < jsonObject.length()) {
JSONObject object = jsonArray.getJSONObject(count);
name = object.getString("name");
subject = object.getString("subject");
message = object.getString("message");
date = object.getString("date");
time = object.getString("time");
sessionManager.getJsonMesssage(message);
DataProvider dataProvider = new DataProvider(name, subject, date, time);
customAdapter.add(dataProvider);
count++;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, String> user = sessionManager.getUserDetails();
String message = user.get(SessionManager.JSON_MESSAGE);
Intent i = new Intent(MessageList.this, MessageDetails.class);
i.putExtra("message", message);
startActivity(i);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all, do not put listview.setOnItemClickListener in a loop. That does nothing. Instead add it in your getView() method of adapter.`
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, String> user = sessionManager.getUserDetails();
String message = user.get(SessionManager.JSON_MESSAGE);
Intent i = new Intent(context, MessageDetails.class);
i.putExtra("message", message);
startActivity(i);
}
});
Then, set your adapter after adding all the list items in while loop.
I am working on a grocery list app and having trouble refreshing the list view after adding a new item. After I add a new item in the database the ListView is not refreshed. If I go in the item details page and then come back to main activity the onCreate is called again and it refreshes it correctly.
If I call the refresh method in the addItemToDb() (on button clicked) method it duplicates my items but does not add them to the database.
Has anyone had this problem before???
Here is the code:
The list view adapter
public class ItemListViewAdapter extends ArrayAdapter<ItemModel> {
Activity activity;
int layoutResource;
ArrayList<ItemModel> itemModelArrayList = new ArrayList<>();
public ItemListViewAdapter(Activity act, int resource, ArrayList<ItemModel> data) {
super(act, resource, data);
activity = act;
layoutResource = resource;
itemModelArrayList = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
return itemModelArrayList.size();
}
#Override
public ItemModel getItem(int position) {
return itemModelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null || (row.getTag()) == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResource, null);
holder = new ViewHolder();
holder.hItemName = (TextView) row.findViewById(R.id.custom_row_productName);
holder.hItemPrice = (TextView) row.findViewById(R.id.custom_row_productPrice);
holder.hItemType = (TextView) row.findViewById(R.id.custom_row_productType);
holder.hCheckBox = (CheckBox) row.findViewById(R.id.custom_row_checkBox);
holder.hItemEdit = (ImageView) row.findViewById(R.id.custom_row_edit);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.hModel = getItem(position);
holder.hItemName.setText(holder.hModel.getItemName());
holder.hItemPrice.setText(String.valueOf(holder.hModel.getItemPrice()));
holder.hItemType.setText(holder.hModel.getItemType());
holder.hItemEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int itemID = holder.hModel.getItemId();
String itemName = holder.hModel.getItemName();
String itemPrice = String.valueOf(holder.hModel.getItemPrice());
String itemType = holder.hModel.getItemType();
String itemDate = holder.hModel.getItemDate();
Intent intent = new Intent(activity, ItemDetail.class);
intent.putExtra("id", itemID);
intent.putExtra("product", itemName);
intent.putExtra("price", itemPrice);
intent.putExtra("type", itemType);
intent.putExtra("date", itemDate);
startActivity(activity, intent, null);
}
});
return row;
}
public class ViewHolder {
ItemModel hModel;
TextView hItemName;
TextView hItemPrice;
TextView hItemType;
TextView hItemDate;
CheckBox hCheckBox;
ImageView hItemEdit;
}
}
And main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHandler = new DatabaseHandler(getApplicationContext());
itemNameText = (EditText) findViewById(R.id.activity_main_productName);
itemPriceText = (EditText) findViewById(R.id.activity_main_productPrice);
itemTypeSpinner = (Spinner) findViewById(R.id.activity_main_spinner);
addButton = (Button) findViewById(R.id.activity_main_addButton);
saveListButton = (FloatingActionButton) findViewById(R.id.activity_main_fab);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.productTypes, R.layout.spinner_item);
itemTypeSpinner.setAdapter(spinnerAdapter);
//USE BUTTONS
addButton.setOnClickListener(this);
saveListButton.setOnClickListener(this);
//LIST_VIEW
listView = (ListView) findViewById(R.id.activity_main_listView);
//calling methods
refreshData();
}
public void refreshData() {
modelArrayListContainer.clear();
//GET ITEMS FROM DB
ArrayList<ItemModel> modelArrayListFromDB = dbHandler.getAllItems();
for (int i = 0; i < modelArrayListFromDB.size(); i++) {
int ditemID = modelArrayListFromDB.get(i).getItemId();
String dItemName = modelArrayListFromDB.get(i).getItemName();
double dItemPrice = modelArrayListFromDB.get(i).getItemPrice();
String dItemType = modelArrayListFromDB.get(i).getItemType();
String dItemDate = modelArrayListFromDB.get(i).getItemDate();
ItemModel newModel = new ItemModel();
newModel.setItemId(ditemID);
newModel.setItemName(dItemName);
newModel.setItemPrice((int) dItemPrice);
newModel.setItemType(dItemType);
newModel.setItemDate(dItemDate);
modelArrayListContainer.add(newModel);
}
//setup Adapter
itemListViewAdapter = new ItemListViewAdapter(MainActivity.this, R.layout.custom_product_layout_activity_main, modelArrayListContainer);
listView.setAdapter(itemListViewAdapter);
itemListViewAdapter.notifyDataSetChanged();
}
public void addItemToDb() {
ItemModel model = new ItemModel();
String spinnerValue = itemTypeSpinner.getSelectedItem().toString();
model.setItemName(itemNameText.getText().toString().trim()); model.setItemPrice(Double.parseDouble((itemPriceText.getText().toString().trim())));
model.setItemType(spinnerValue);
dbHandler.addItem(model);
dbHandler.close();
Log.v(TAG, "::addItemToDb - itemAdded");
}
}
You need to call refreshData() in your addItemToDb function like:
public void addItemToDb() {
ItemModel model = new ItemModel();
String spinnerValue = itemTypeSpinner.getSelectedItem().toString();
model.setItemName(itemNameText.getText().toString().trim()); model.setItemPrice(Double.parseDouble((itemPriceText.getText().toString().trim())));
model.setItemType(spinnerValue);
dbHandler.addItem(model);
dbHandler.close();
Log.v(TAG, "::addItemToDb - itemAdded");
refreshData();
}
But if you need to update data automatically from database, you need to use CursorAdaptor and use Content Providers
UPDATE
Also change your getAllItems() function in dbhandler and include the following statement in the first line of the function:
modelArrayList.clear();
I am learning custom array adapter and i want to do something like if the listview row view is 0(the first row of the listview), i want to have a seperate layout, after that i want another comoon layout for the rest of the list. I have the custom adapter but don't quiet fully understand , how can it be done?. Thank you.
public class NewsFragment extends Fragment{
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
GetNews.CustomAdapter CA;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.news, container, false);
newsList = (ListView) view.findViewById(R.id.newsListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
newsList.setOnItemClickListener(new newsListClick());
return view;
}
public class newsListClick implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SinglePost singleFrag = new SinglePost();
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings","Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{
private final ArrayList<HashMap<String, String>> objects;
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup Parent){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
String getListPos = String.valueOf(newsList.getFirstVisiblePosition());
if(getListPos == "0"){
thisview.setText(getListPos);
}else{
thisview.setText(objects.get(position).get(POST_TITLE));
}
//thisview.setText(getListPos);
return convertView;
}
}//
}
}
Can use getItemViewType to specify types of views list view can have.
Here is some sample example.
Try something like below:
public View getView(int position, View convertView, ViewGroup Parent){
if(position==0){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.first_row_layout,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
String getListPos = String.valueOf(newsList.getFirstVisiblePosition());
if(getListPos == "0"){
thisview.setText(getListPos);
}else{
thisview.setText(objects.get(position).get(POST_TITLE));
}
}else{
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.otherlayout_view,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
String getListPos = String.valueOf(newsList.getFirstVisiblePosition());
if(getListPos == "0"){
thisview.setText(getListPos);
}else{
thisview.setText(objects.get(position).get(POST_TITLE));
}
}
//thisview.setText(getListPos);
return convertView;
}
I did something like this guys, is it right way to do it? It does the thing i want.
public View getView(int position, View convertView, ViewGroup Parent){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
int getListPos = newsList.getFirstVisiblePosition();
//i set the count starting 0 and saved in the hashmap array
//to compare the first result with the first position of listview
int count = Integer.parseInt(objects.get(position).get("ListCount"));
if(getListPos == count) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE));
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
}else{
thisview.setText("Normal line");
}
return convertView;
}
Hi i am writing a program using custom listview with checkbox. My intention is to start a new activity when clicking a button (Add) and the new activity displays the selected values from the listview.I am getting error when i try to add the values
the error occuring line is
selectedItems.add(adapter.getItem(position));
if i comment this line then i can check the box but it shows eror when i click "Add" button.
here is my complete code.
My mainactivity
HomePage.java
public class HomePage extends Activity {
private ListView listView1;
ListAdapter adapter;
Button btn;
SparseBooleanArray checkedValue;
ArrayList<List> selectedItems;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
List device_data[] = new List[]
{
new List(R.drawable.ic_pic , "Actvity1"),
new List(R.drawable.ic_pic, "Actvity2"),
new List(R.drawable.ic_pic, "Actvity3"),
new List(R.drawable.ic_pic, "Actvity4"),
new List(R.drawable.ic_pic, "Actvity5")
};
ListAdapter adapter = new ListAdapter(this, R.layout.list_viewrow, device_data);
listView1 = (ListView)findViewById(R.id.listView1);
View header = (View)getLayoutInflater().inflate(R.layout.listview_header, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
Log.i("check box status", ""+ListAdapter.ListHolder.class);
btn= (Button)findViewById(R.id.add);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] outputStrArr = new String[selectedItems.size()];
checkedValue= listView1.getCheckedItemPositions();
for (int i = 0; i < selectedItems.size(); i++) {
outputStrArr[i] = selectedItems.get(i).toString();
}
Intent intent = new Intent(getApplicationContext(),
CheckedValues.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", outputStrArr);
// Add the bundle to the intent.
intent.putExtras(b);
startActivity(intent);
}
});
}
private class ListAdapter extends ArrayAdapter<List> {
Context context;
int layoutResourceId;
boolean checkvalue;
List data[] = null;
public ListAdapter(Context context, int layoutResourceId, List[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
final ListHolder holder;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ListHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.checkbox=(CheckBox) row.findViewById(R.id.check);
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
selectedItems.add(adapter.getItem(position));
}
});
row.setTag(holder);
}
else
{
holder = (ListHolder)row.getTag();
}
List list = data[position];
holder.txtTitle.setText(list.title);
holder.imgIcon.setImageResource(list.icon);
return row;
}
class ListHolder
{
ImageView imgIcon;
TextView txtTitle;
CheckBox checkbox;
}
}
}
and my second activity
CheckedValues.java
public class CheckedValues extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checked_values);
Bundle b = getIntent().getExtras();
String[] resultArr = b.getStringArray("selectedItems");
ListView lv = (ListView) findViewById(R.id.outputList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, resultArr);
lv.setAdapter(adapter);
}
}
thanks in advance..
initialize the "ArrayList"
ArrayList<List> selectedItems;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
selectedItems = new ArrayList<List>();
}
I've got a ListView with a 'show next results' button. The list is filled by a custom adapter extending BaseAdapter. Using it as shown below, only the new results are shown.
How can I append the new results to the list?
ListView listView = (ListView)findViewById(android.R.id.list);
// Show next results button
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = getIntent();
i.putExtra("firstIndex", mFirstIndex + NRES_PER_PAGE);
i.putExtra("itemCount", NRES_PER_PAGE);
startActivity(i);
}
});
mItems = json.getJSONArray("data");
setListAdapter(new ItemAdapter(ItemList.this, mType, mItems));
FIX
ListActivity
public class ItemList extends MenuListActivity{
ItemAdapter mItemAdapter;
Integer mFirstIndex = 0;
JSONArray mItems = new JSONArray();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list);
// Set data adapter
mItemAdapter = new ItemAdapter(ItemList.this, mType, mItems);
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
setListAdapter(mItemAdapter);
new GetItemInfoList().execute();
}
private class GetItemInfoList extends AsyncTask<Void, Void, JSONObject> {
protected JSONObject doInBackground(Void... params) {
// Set POST data to send to web service
List<NameValuePair> postData = new ArrayList<NameValuePair>(2);
postData.add(new BasicNameValuePair("firstindex", Integer.toString(mFirstIndex)));
postData.add(new BasicNameValuePair("itemscount", Integer.toString(ITEM_COUNT)));
JSONObject json = RestJsonClient.getJSONObject(URL_ITEMINFOLIST, postData);
return json;
}
protected void onPostExecute(JSONObject json) {
try {
// Get data from json object and set to list adapter
JSONArray jsonArray = json.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++)
mItems.put(jsonArray.get(i));
mItemAdapter.notifyDataSetChanged();
ListView listView = (ListView)findViewById(android.R.id.list);
View footerView = ((LayoutInflater)ItemList.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
listView.addFooterView(footerView);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progressDialog = MyProgressDialog.show(ItemList.this, null, null);
mFirstIndex = mFirstIndex + ITEM_COUNT;
new GetItemInfoList().execute();
}
});
} catch (JSONException e) {
}
}
}
}
Adapter
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private JSONArray mItems;
private ImageLoader mImageLoader;
private int mCategory;
public ItemAdapter(Context context, int category, JSONArray items) {
mContext = context;
mInflater = LayoutInflater.from(context);
mItems = items;
mCategory = category;
this.mImageLoader = new ImageLoader(context, true);
}
public int getCount() {
return mItems.length();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_row, null);
holder = new ViewHolder();
holder.listitem_pic = (ImageView) convertView.findViewById(R.id.listitem_pic);
holder.listitem_desc = (TextView) convertView.findViewById(R.id.listitem_desc);
holder.listitem_title = (TextView) convertView.findViewById(R.id.listitem_title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
JSONObject item = mItems.getJSONObject(position);
String listitem_pic = item.getString("picture");
holder.listitem_pic.setTag(listitem_pic);
mImageLoader.DisplayImage(listitem_pic, (Activity)mContext, holder.listitem_pic);
holder.listitem_title.setText(item.getString("title"));
holder.listitem_desc.setText(item.getString("desc"));
}
catch (JSONException e) {
}
return convertView;
}
static class ViewHolder {
TextView listitem_title;
ImageView listitem_pic;
TextView listitem_desc;
}
}
It depends on your implementation of ItemAdapter, I'd recommend holding a reference to ItemAdapter, then updating the data set behind it and then calling notifyDataSetChanged() on it. something like:
ItemAdapter ia = new ItemAdapter(ItemList.this, mType, mItems);
setListAdapter(ia);
footerView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mItems.append(newItems);
ia.notifyDataSetChanged();
}
});
It is tricky without knowing what data you are using or whether you have the entire data set available at the start.