custom list view with check Box does not work - android

I have a problem my custom List view.I have data in hash map and add into array list which is shown in below code.what is my problem is in my hash map contain 20 values and i try set into the list view but first data only display other or not.Thanks advance
This is my CustomAdapter
package com.example.node10.databasetesting;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.example.node10.databasetesting.DataBase.*;
public class ListViewEmployee extends AppCompatActivity implements View.OnClickListener {
private SimpleCursorAdapter dataAdapter;
private Button btn_view;
private Button btn_submit;
ArrayList<HashMap<Integer,String>> emp;
HashMap<Integer,String> map;
Set<Integer> keyValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_employee);
DataBase dataBase=new DataBase(this);
map=new HashMap<>();
map=dataBase.getValueEmpTable();
emp=new ArrayList<HashMap<Integer, String>>();
keyValue=map.keySet();
emp.add(map);
btn_view= (Button) findViewById(R.id.id_btn_emp_view);
btn_view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.id_btn_emp_view){
displayList();
// selectItem();
}
}
private void displayList() {
//create the Arrayt adapter
ListView listview= (ListView) findViewById(R.id.id_listview);
final MyAdapter adapter=new MyAdapter(this,R.layout.custom_listview,emp);
listview.setAdapter(adapter);
}
public class MyAdapter extends ArrayAdapter<HashMap<Integer,String>>{
boolean[] checkBoxState;
ViewHolder viewholder;
public MyAdapter(Context context, int resource,ArrayList<HashMap<Integer,String>> map) {
super(context, resource, map);
// create the boolean array for check box selection
checkBoxState= new boolean[map.size()];
}
// create the class for caching the view
class ViewHolder{
TextView txtView;
CheckBox checkBox;
}
#Override
public View getView( final int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater objlayout= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=objlayout.inflate(R.layout.custom_listview,null);
viewholder=new ViewHolder();
viewholder.txtView= (TextView) convertView.findViewById(R.id.id_checkbox_textview);
viewholder.checkBox= (CheckBox) convertView.findViewById(R.id.id_checkbox);
convertView.setTag(viewholder);
}else{
viewholder = (ViewHolder) convertView.getTag();}
// viewholder.txtView.setText(emp.get(position).toString());
viewholder.txtView.setText(emp.get(position).get(position+1).toString());
viewholder.checkBox.setChecked(checkBoxState[position]);
viewholder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
}
});
return convertView;
}
}
}

Now you put to your adapter ArrayList of HashMap. I don't know why are you doing that, but now your ArrayList emp contains ony one element - that was added in line
emp.add(map);
So, ArrayAdapter for array with size = 1 will show 1 elemet.
If you want to show in list all elements from your map. I suggest to use
ArrayList emp and comvert map to list by using map.values()
ArrayList<String> emp = (ArrayList<String>)map.values();
Then change your adapter to
public class MyAdapter extends ArrayAdapter<String>

Related

Android parse.com listView crashing

i am attempting to create this app which has a listView and when i click on an item in the listView it displays more information about the clicked item. I dont know how to fix this problem. i am getting the following from my log
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
at com.example.velvetdev01.parselistclick.MainActivity$1.onItemClick(MainActivity.java:50)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
and here is my code
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseQueryAdapter;
import java.util.List;
//import android.widget.ArrayAdapter;
public class MainActivity extends Activity {
private CustomAdapter urgentTodosAdapter;
private ParseQueryAdapter<ParseObject> mainAdapter;
private ListView listView;
List<ParseObject> object;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
mainAdapter = new ParseQueryAdapter<ParseObject>(this, "RestaurantDetail");
urgentTodosAdapter = new CustomAdapter(this);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(urgentTodosAdapter);
urgentTodosAdapter.loadObjects();
// Binds the Adapter to the ListView
listView.setAdapter(urgentTodosAdapter);
// Capture button clicks on ListView items
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(MainActivity.this, SingleItemView.class);
// Pass data "name" followed by the position
intent.putExtra("Name", object.get(i).getString("Name"));
// Open SingleItemView.java Activity
startActivity(intent);
}
});
}
}
and my custom adapter
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.parse.ParseFile;
import com.parse.ParseImageView;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
public class CustomAdapter extends ParseQueryAdapter<ParseObject> {
public CustomAdapter(Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("RestaurantDetail");
/* query.whereEqualTo("Name", true);*/
return query;
}
});
}
#Override
public View getItemView(ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.activity_main, null);
}
super.getItemView(object, v, parent);
ParseImageView todoImage = (ParseImageView) v.findViewById(R.id.icon);
ParseFile imageFile = object.getParseFile("Logo");
if (imageFile != null) {
todoImage.setParseFile(imageFile);
todoImage.loadInBackground();
}
TextView titleTextView = (TextView) v.findViewById(R.id.textView3);
titleTextView.setText(object.getString("Name"));
return v;
}
}
Here is the class i am trying to display the detailed information
#ParseClassName("RestaurantDetail")
public class SingleItemView extends Activity {
// Declare Variables
protected TextView txtname;
String Name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from singleitemview.xml
setContentView(R.layout.single_item_view);
txtname = (TextView) findViewById(R.id.name);
// Retrieve data from MainActivity on item click event
Intent random1 = getIntent();
// Get the name
Name = random1.getStringExtra("Name");
// Locate the TextView in singleitemview.xml
txtname = (TextView) findViewById(R.id.name);
// Load the text into the TextView
txtname.setText(Name);
}
}

How to reset the whole View by clicking the delete Button

I have made a custom View which contains an ImageView, a TextView and a delete Button.
I want to reset the particular View when I click the delete Button associated with it.
Please tell how to implement this.
Here is my MainActivity.java
package com.khurana.nikhil.list1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ListView lv;
TextView tv1, tv2;
View v1;
public String[] s = {"nikhil", "mukul", "kunal"};
public int[] img = {R.drawable.rty, R.drawable.sf, R.drawable.rty};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
CustomAdapter cad = new CustomAdapter(MainActivity.this, s, img);
lv.setAdapter(cad);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,View v,int position,long id)
{
Toast.makeText(MainActivity.this,"You clicked "+s[position],Toast.LENGTH_SHORT).show();
}
});
}
}
Here is CustomAdapter.java
package com.khurana.nikhil.list1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<String>{
Context c1;
String s1[];
int s2[];
CustomAdapter(Context c,String s[],int s3[])
{
super(c,R.layout.tcustom,s);
this.c1=c;
this.s1=s;
this.s2=s3;
}
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
return v;
}
}
((LinearLayout)yourView.getParent()).removeView(yourView);
or you can call from the layout directly
yourRelativeLayout.removeView(yourView)
I would recommend to use an ArrayList instead of a String[] in your Adapter class. It makes it a lot easier to delete or edit a View and the associated data behind it. I used this post to convert your String[] to an ArrayList, delete the item and convert back to String[].
This should work on button click:
In your Adapter class:
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
bt.setTag(position); //important so we know which item to delete on button click
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
int positionToRemove = v.getTag(); //get the position of the view to delete stored in the tag
removeItem(positionToRemove); //remove the item
}
});
return v;
}
public void removeItem(int position){
//convert array to ArrayList, delete item and convert back to array
ArrayList<String> a = new ArrayList<>(Arrays.asList(s1));
a.remove(i);
strings = new String[a.size()];
s1= a.toArray(strings);
notifyDataSetChanged(); //refresh your listview based on new data
}
#Override
public int getCount() {
return s1.length;
}
#Override
public String getItem(int position) {
return s1[position];
}
View visibility to GONE will not delete your view from memory as well. Please be specific, do you want to retain your view for future?
If you are working in a listview you should call notifyDataSetChanged() the adapter. your getView() method can be like:
action on button can be like this
Button bt=(Button)v.findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s1 = ArrayUtils.remove(s1, position);
s2 = ArrayUtils.remove(s2, position);
notifyDataSetChanged();
}
});
If you want the view to disappear:
yourView.setVisibility(View.GONE);
EDIT: To get the parent view of the button: Android: Making changes to a button's parent view

android:checkbox in listview

What I've done so far is detecting mp3 files and display it with a checkbox in lisview, my problem is once i checked the item and scrolled down, the item that i checked before is lost.
This is my code:
this is the adapter
package com.example.cameraapp;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<Model>{
Model[] modelItems = null;
Context context;
public CustomAdapter(Context context, Model[] resource) {
super(context,R.layout.songlayout,resource);
// TODO Auto-generated constructor stub
this.context = context;
this.modelItems = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(R.layout.songlayout, parent, false);
TextView name = (TextView) convertView.findViewById(R.id.songsTexView);
CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
name.setText(modelItems[position].getName());
if(modelItems[position].getValue() == 1)
cb.setChecked(true);
else
cb.setChecked(false);
return convertView;
}
}
and this is the mainactivity
package com.example.cameraapp;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.widget.ListView;
public class FinalChoice extends Activity {
ListView lv;
int chuba=0;
Model[] modelItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview1hold);
lv = (ListView) findViewById(R.id.listView1);
String mp3Directory = "/Music";
String directoryPath= Environment.getExternalStorageDirectory().getAbsolutePath()+mp3Directory;
List<File> list = getMP3Files(directoryPath);
modelItems = new Model[list.size()];
//print in LogCat the list of .mp3:
for(int a=0;a<list.size();a++){
modelItems[a]=new Model( list.get(a).getName(), 0);
}
CustomAdapter adapter = new CustomAdapter(this, modelItems);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public List<File> getMP3Files(String directory) {
List<File> files = new ArrayList<File>();
File folder = new File(directory);
for (File file : folder.listFiles()) {
if (file.isFile()) {
if (file.getName().endsWith(".mp3") || file.getName().endsWith(".MP3")) {
files.add(file);
}
}
}
return files;
}
}
Keep track of all the checked items and using that set selection of check boxes in getView method. Whenever the selection is changes update your values which keep track of all the selections.
This might help you...
When scrolling custom ListView, the checkbox value changes

Modifying element of a listView how to get access to it

I learned that in order to modify row in a listView I need to gain access eg via adapter.getItem(position) but I have no idea how to work this around. Should I post any code please let me know.
Here is my EditListItemDialog file:
package com.example.classorganizer;
import java.util.ArrayList;
import java.util.List;
import com.example.classorganizer.Monday.DiaryAdapter;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
class EditListItemDialog extends Dialog implements View.OnClickListener {
private View editText;
private DiaryAdapter adapter;
// public EditListItemDialog(Context context, List<String> fragment_monday) { //first constructor
// super(context);
// this.fragment_monday = fragment_monday;
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
private List<String> fragment_monday;
public EditListItemDialog(Context context, DiaryAdapter adapter) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
adapter.notifyDataSetChanged();
dismiss();
}
}
You will have to implement an OnItemClickListener which will be able to tell you what item has been clicked. For example:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
See the official Android documentation for more information.
package com.example.classorganizer;
import java.util.ArrayList;
import java.util.List;
import com.example.classorganizer.Monday.DiaryAdapter;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class EditListItemDialog extends Activity {
ListView listView ;
private View editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
listView = (ListView) findViewById(R.id.list)
String[] values = new String[] { "Automotive", "Banking", "Consumer Electronics",
"Education", "HealthCare and Life Sciences","Industrial Automation","Printing and
Imaging","Manufacturing","Media and
Entertainment","Networking","Retail","Telecom"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
}
Use This code for simple Listview..

how to use a custom button in a list to redirect the user to another activity

I've written a big code and I've used a list view within one of my task layouts :
I want to know how I can make a listener for each update button in this case in order to move to another activity , I know how to use more than one activity and moves between them But I want to know how to make a listener only .
The custom adapter code :
package com.example.task_9;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class TempLyaout extends ArrayAdapter<String> {
Context context;
ArrayList<String> sa;
public TempLyaout(Context context , ArrayList<String> sa) {
super(context,R.layout.temp,sa);
this.context=context;
this.sa = sa;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater l = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View rowView = l.inflate(R.layout.temp, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView1);
Button update = (Button) rowView.findViewById(R.id.button1);
// myDb.open();
// Cursor cursor= myDb.getRowByName(sa.get(position));
// myDb.updateRowByName(cursor.getInt(DBAdapter.COL_ROWID), sa.get(position), cursor.getString(DBAdapter.COL_PASSWD), cursor.getInt(DBAdapter.COL_AGE), isAdmin);
// myDb.close();
textView.setText(sa.get(position));
return rowView;
}
}
This is the related class :
package com.example.task_9;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class UsersActivity extends Activity {
Intent redirect;
ListView list;
ArrayList<String> sa;
DBAdapter myDb;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.users);
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
openDB();
/*********************************************/
Cursor cursor = myDb.getAllRows();
cursor.moveToFirst();
ArrayList<String> ha = new ArrayList<String>();
while(cursor.moveToNext()) {
ha.add(cursor.getString(DBAdapter.COL_NAME));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ha);
list.setAdapter(new TempLyaout(UsersActivity.this,ha));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
} // end onStart method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
} // end openDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void closeDB() {
myDb.close();
} // end closeDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
}// end main class
In your getView
Button update = (Button) rowView.findViewById(R.id.button1);
update.setOnClickListener(mClickListener);
Then
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ListActivtiy.this,SecondActivity.class);
startActivity(intent);
}
};
Also use a viewholder for smooth scrolling and performance
http://developer.android.com/training/improving-layouts/smooth-scrolling.html

Categories

Resources