Uri argument and LoaderCallbacks - java

I have four class :
MainActivity.java - MyAdapter.java - MyDataBase.java - MyListActivity.java
now, what is Uri in the MyListActiviy ? How can I fill it ?
when I Click "showlist_btn" button in MainActivity, a list without content is displayed ! why ?
MainActivity:
package com.example.ex22;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText edittext ;
Button add_btn ;
Button showlist_btn ;
MyDataBase mydatabase ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydatabase = new MyDataBase(MainActivity.this);
edittext = (EditText)findViewById(R.id.edittext);
showlist_btn = (Button)findViewById(R.id.showlist_btn);
add_btn = (Button)findViewById(R.id.add_btn);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String str = edittext.getText().toString();
mydatabase.addName(str);
edittext.setText("");
}
});
showlist_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, MyListActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyAdapter:
package com.example.ex22;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter {
List<String> mylist ;
LayoutInflater inflater ;
public MyAdapter(Context context){
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mylist.size();
}
void getList(List<String> list){
mylist = list ;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewholder ;
if(convertView == null){
convertView = inflater.inflate(R.layout.row_for_list, null);
viewholder = new ViewHolder();
viewholder.text = (TextView)convertView.findViewById(R.id.textview_forrow);
convertView.setTag(viewholder);
}else {
viewholder = (ViewHolder)convertView.getTag();
}
viewholder.text.setText(mylist.get(position));
return convertView;
}
static class ViewHolder{
TextView text ;
}
}
MyDataBase:
package com.example.ex22;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyDataBase extends SQLiteOpenHelper {
private final static String DB_NAME = "mydb" ;
private final static String TABLE_NAME = "mytable" ;
//private static final String NAME = "name" ;
private final static String NAME_COLOUM = "_name" ;
private static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME + "("
+ NAME_COLOUM + " TEXT" + ")";
public MyDataBase(Context context){
super(context,DB_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
public void addName(String str){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_COLOUM, str);
db.insert(TABLE_NAME, null, values);
db.close();
}
public List<String> getAllNames(){
List<String> list = new ArrayList<String>() ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM "+ TABLE_NAME, null);
if(c.moveToFirst()){
do{String str = c.getString(0);
list.add(str);
}while(c.moveToNext());
}
return list ;
}
public String getCulomName(){
return this.NAME_COLOUM;
}
}
MyListActivity:
package com.example.ex22;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.SimpleCursorAdapter;
public class MyListActivity extends ListActivity
implements LoaderCallbacks<Cursor>{
SimpleCursorAdapter simplecursorradapter ;
MyDataBase mydb ;
CursorLoader cursorloader ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//setContentView(R.layout.show_list);
mydb = new MyDataBase(this);
String[] from = new String[] { mydb.getCulomName() };
int[] to = new int[]{
R.id.forlist
};
simplecursorradapter = new SimpleCursorAdapter(this, android.R.layout.simple_expandable_list_item_2, null,
from , to ,0);
setListAdapter(simplecursorradapter);
LoaderManager loadermanager = getLoaderManager();
loadermanager.initLoader(0, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
String[] projection = {mydb.getCulomName()};
final String SCHEME = "content";
// The provider's authority
final String AUTHORITY = "com.example.ex22";
final Uri src = Uri.parse(SCHEME + "://" + AUTHORITY);
Uri uri = Uri.withAppendedPath(src, "mytable");
cursorloader = new CursorLoader(this, uri, projection, null, null, null);
return cursorloader;
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
// TODO Auto-generated method stub
simplecursorradapter.swapCursor(arg1);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
simplecursorradapter.swapCursor(null);
}
}
activity_main :
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="#+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Write Your Name..."
/>
<Button
android:id="#+id/add_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add Name"
/>
<Button
android:id="#+id/showlist_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Show Name List"
/>
</LinearLayout>
forlist:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/forlist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
row_for_list:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textview_forrow"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="40sp"
/>
</LinearLayout>
show_list:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

Related

JSON - Help Converting JSONArray to Arraylist and populate a listview.

I am fairly new to android and java. I am trying to add JSON data to a listview. I have the JSON data coming in and printing to log, but I am having a hard time getting the data to the list view. I've tried and arraylist on row numbers and it works, but don't know how to get the JSON data there. Any pointers or advice would be appericated.
I am looking for a result Like
(Keys)ID Name Tourn_ID
(Values) 1 Tournamnet1 MI2016
(Values) 2 Tournamnet2 UT2016
(Values) 3 Tournamnet4 USNC2016
etc.
Here is my code Java.
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static android.R.*;
import static android.R.layout.simple_list_item_1;
import static java.util.Arrays.asList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("http://www.goalballscoreboard.net/mobile/downloads/WebServices/Tournnames/Tournnames.php?rows=all");
ListView tournListView = (ListView) findViewById(R.id.tournListView);
final ArrayList<String> myTournList = new ArrayList<String>(asList("ROW 1", "ROW 2", "Row3"));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, simple_list_item_1, myTournList);
tournListView.setAdapter(arrayAdapter);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String tournInfo = jsonObject.getString("posts");
Log.i("Tourn INFO", tournInfo);
JSONArray arr = new JSONArray(tournInfo);
List<String> list = new ArrayList<String>();
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
JSONObject jsonObjectPost = jsonPart.getJSONObject("post");
//Log.i("Each Tournament Object", jsonPart.getString("post"));
Log.i("ID", jsonObjectPost.getString("ID"));
Log.i("Name of Tournament", jsonObjectPost.getString("NAME"));
Log.i("TOURN_ID", jsonObjectPost.getString("TOURN_ID"));
String id = jsonObjectPost.get("ID").toString();
String name = jsonObjectPost.get("NAME").toString();
String tournID = jsonObjectPost.get("TOURN_ID").toString();
list.add(jsonObjectPost.getString("ID") + ", " + jsonObjectPost.getString("NAME") + "," + jsonObjectPost.getString("TOURN_ID") + "\n");
}
System.out.println("" + list.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Create a JAVA file named Model.java
public class Model {
public String ID ;
public String Name;
public Tourn_ID;
}
Now at the time of parsing data
ArrayList<Model> modelArrayList = new ArrayList();
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
JSONObject jsonObjectPost = jsonPart.getJSONObject("post");
Model model;
model.ID = jsonObjectPost.get("ID").toString();
model.Name = jsonObjectPost.get("NAME").toString();
Model.Tourn_ID = jsonObjectPost.get("TOURN_ID").toString();
modelArrayList .add(model);
}
Adapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter{
ArrayList<Model> result = new ArrayList();
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(Context context, ArrayList<Model> result) {
// TODO Auto-generated constructor stub
this.result=result;
this.context=context;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.size;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv,tv2,tv3;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.custom_adapter, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.tv2=(TextView) rowView.findViewById(R.id.textView2);
holder.tv3=(TextView) rowView.findViewById(R.id.textView3);
holder.tv.setText(result[position].ID);
holder.tv2.setText(result[position].Name);
holder.tv3.setText(result[position].Tour_ID);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
in custom_adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:text="TextView" />
</LinearLayout>
now listview
listview = (Listview).findViewById(R.id.idOfYpurListview);
Adapter adapter = new Adapter(Activity.this,modelArrayList);
listview.setAdapter(adapter);

List view not working in android

I am trying to make an app of notifications for my college project.
I am trying to create a Customized Adapter for a listview , but the activity containing the ListView does not show anything. I think I have done something wrong in the getView() method in CustomAdapter.java.
CustomAdapter class is used to created the child views for the the listview. listviechild.xml defines the layout for single row in the listview tith xml file - listactivity.xml
package com.example.client_nic;
import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter {
public Context context =null;
public ArrayList<String> nam = null;
public ArrayList<String> date= null;
public ArrayList<String> time = null;
LayoutInflater inflater =null;
public CustomAdapter(Context context, ArrayList<String> nam,
ArrayList<String> date, ArrayList<String> time) {
super();
nam = new ArrayList<String>();
date = new ArrayList<String>();
time = new ArrayList<String>();
this.context = context;
this.nam = nam;
this.date = date;
this.time = time;
inflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return nam.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int pos, View view, ViewGroup arg2) {
// TODO Auto-generated method stub
Log.e("name",nam.get(pos));
Log.e("date",date.get(pos));
Log.e("time", time.get(pos));
view = inflater.inflate(R.layout.listviewchild, arg2,false);
if(view.isActivated()){
Toast.makeText(context, "yes",Toast.LENGTH_SHORT).show();
}
TextView nametv = (TextView)view.findViewById(R.id.textView1);
TextView datetv = (TextView)view.findViewById(R.id.textView2);
TextView timetv = (TextView)view.findViewById(R.id.textView3);
nametv.setText(nam.get(pos));
datetv.setText(date.get(pos));
timetv.setText(time.get(pos));
return view;
}
}
listviewchild.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:height="30dp" />
<TextView android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:height="20dp"
android:layout_below="#+id/textView1"
/>
<TextView android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:height="20dp"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/textView2"
android:layout_below="#+id/textView1"
/>
</RelativeLayout>
listactivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
Try the following:
package com.example.client_nic;
import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class CustomAdapter extends BaseAdapter {
public Context context =null;
public ArrayList<String> nam = null;
public ArrayList<String> date = null;
public ArrayList<String> time = null;
LayoutInflater inflater = null;
public CustomAdapter(Context context, ArrayList<String> nam,
ArrayList<String> date, ArrayList<String> time) {
nam = new ArrayList<String>();
date = new ArrayList<String>();
time = new ArrayList<String>();
this.context = context;
this.nam = nam;
this.date = date;
this.time = time;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return nam.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int pos, View view, ViewGroup arg2) {
// TODO Auto-generated method stub
Log.e("name",nam.get(pos));
Log.e("date",date.get(pos));
Log.e("time", time.get(pos));
view = inflater.inflate(R.layout.listviewchild, arg2, false);
if(view.isActivated()){
Toast.makeText(context, "yes",Toast.LENGTH_SHORT).show();
}
TextView nametv = (TextView)view.findViewById(R.id.textView1);
TextView datetv = (TextView)view.findViewById(R.id.textView2);
TextView timetv = (TextView)view.findViewById(R.id.textView3);
nametv.setText(nam.get(pos));
datetv.setText(date.get(pos));
timetv.setText(time.get(pos));
return view;
}
}
This should properly inflate your views and work. If there are other problems, you may be passing empty data to to the Adapter.
Couple of side notes
1) You are passing three ArrayLists to fill the data for your ListView. Why not just pass a single array list with custom Java objects? The fields for the java objects would be name, data, time.
i.e:
public class MyObject{
public String name;
public String date;
public String time;
MyObject(String name, String date, String time){
this.name = name;
this.date = date;
this.time = time;
}
//define getters and setters...
}
and:
public CustomAdapter(Context context, ArrayList<MyObject> objs) {
...
...
}
2) You are inflating the view each time. Instead, use the ViewHolder Pattern to hold the views data rather than re-drawing this and looking up resources each time in your application. Android makes use of recycling views so you want to maximize on this and save resources and reduce delays from loading views each time (lots of overhead!). I will not provide an example on this for you, but look up that link to find out how to do this yourself!
By looking at your code I think that the instance varibles of class CustomAdapter (ArrayList s) nam, date and time are not getting filled with the contents of the corresponding ArrayList passed to the constructor due to which the Activity containing ListView is displaying nothing.
Replace the constructor with the following code
public CustomAdapter(Context context, ArrayList<String> nam,
ArrayList<String> date, ArrayList<String> time) {
super();
this.context = context;
this.nam.addAll(nam);
this.date.addAll(date);
this.time.addAll(time);
inflater =LayoutInflater.from(context);
}
I think this will solve your problem.

Popup window not showing up with spinner item selection?

On Clicking the spinner item need to show the popup window but its not showing up, only i can see the toast notification.
Log: system.err
java.lang.IllegalStateException: System services not available to Activities before onCreate()
My Code Below
MainActivity.java
package com.example.newapplication;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Spinner;
import com.example.newapplication.service;
public class MainActivity extends Activity {
Button btnClosePopup;
//Button OpenPopup;
ArrayList array;
service ser = new service(array);
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner1);
/*OpenPopup = (Button) findViewById(R.id.button1);
OpenPopup.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
initiatepopupwindow();
}
});
*/
array = ser.getArrayList();
Log.d("TAG","" +array);
//for(int i=0;i<array.length();i++){
//}
ArrayAdapter<String> dataadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array);
dataadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataadapter);
addListenerOnSpinnerItemSelected();
}
private PopupWindow pwindo;
private void addListenerOnSpinnerItemSelected() {
// TODO Auto-generated method stub
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
#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 void initiatepopupwindow() {
// TODO Auto-generated method stub
try{
Log.d("TAG", "" +"Inside popupwindow");
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screen_popup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 300, 370, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
}
catch (Exception e) {
e.printStackTrace();
}
}
private OnClickListener cancel_button_click_listener = new OnClickListener() {
public void onClick(View v) {
pwindo.dismiss();
}
};
}
Listener for spinner event.
CustomOnItemSelectedListener.java
package com.example.newapplication;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.example.newapplication.MainActivity;
public class CustomOnItemSelectedListener implements OnItemSelectedListener{
MainActivity main = new MainActivity();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
main.initiatepopupwindow();
Toast.makeText(parent.getContext(), parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
screenpopup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup_element"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#444444"
android:orientation="vertical"
android:padding="10sp" >
<TextView
android:id="#+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
android:text="Hello!" />
<Button
android:id="#+id/btn_close_popup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Close" />
</LinearLayout>
activity_main layout
<RelativeLayout 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"
android:background="#drawable/lightbackground"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="23dp"
android:layout_marginTop="32dp"
android:text="Welcome to MyApp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="21dp" />
</RelativeLayout>
remove your CustomOnItemSelectedListener.java class
and then use this code
public class MainActivity extends Activity {
Button btnClosePopup;
// Button OpenPopup;
ArrayList array;
service ser = new service(array);
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner1);
/*
* OpenPopup = (Button) findViewById(R.id.button1);
* OpenPopup.setOnClickListener(new OnClickListener(){
*
* #Override public void onClick(View v) { // TODO Auto-generated method
* stub initiatepopupwindow(); }
*
* });
*/
array = ser.getArrayList();
Log.d("TAG", "" + array);
// for(int i=0;i<array.length();i++){
// }
ArrayAdapter<String> dataadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, array);
dataadapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataadapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
initiatepopupwindow();
Toast.makeText(getApplicationContext(), array.get(arg2) + "",
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private PopupWindow pwindo;
#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 void initiatepopupwindow() {
// TODO Auto-generated method stub
try {
Log.d("TAG", "" + "Inside popupwindow");
LayoutInflater inflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.screenpopup,
(ViewGroup) findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 300, 370, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
btnClosePopup.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
private OnClickListener cancel_button_click_listener = new OnClickListener() {
public void onClick(View v) {
pwindo.dismiss();
}
};
}
In place of layout pass spinner object of your view:
replace
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
with
pwindo.showAtLocation(spinner, Gravity.CENTER, 0, 0);
And to open popup window just below your spinner use below code
pwindo.showAsDropDown(spinner, 0, 0);
Update your CustomOnItemSelectedListener class as:
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
Context mCtx;
public CustomOnItemSelectedListener(Context ctx) {
this.mCtx = ctx;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
((MainActivity) mCtx).initiatepopupwindow();
Toast.makeText(parent.getContext(),
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG)
.show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

no such column _id Android,Java,SQL

I'm pretty new to Java and Android apps, just started several weeks ago, everything went pretty well until now, when I stuck for several hours with a problem I cannot resolve, even with checking dozens of threads here.
I'm working on pretty simple android app that is supposed to show movies and years from a database, with a possibility to add record, show them all, search by a year or title. I stopped on a problem with
no such column _id (code 1): , while compiling SELECT _id, title, year FROM movies
I will be grateful for any help.
There are my files :
MainActivity
package com.example.imdbproject;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MainActivity extends Activity {
ListView moviesList;
Button searchYear;
Button searchTitle;
Button showAll;
Button addbtn;
Cursor cursor;
adapter adapter_ob;
MySQLiteHelper helper_ob;
SQLiteDatabase db_ob;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitDataBase();
moviesList = (ListView)findViewById(R.id.listView1);
searchYear = (Button)findViewById(R.id.buttonYear);
searchTitle =(Button)findViewById(R.id.buttonTitle);
addbtn = (Button)findViewById(R.id.buttonAdd);
showAll = (Button)findViewById(R.id.buttonShowAll);
adapter_ob = new adapter(this);
String[] from = { helper_ob.KEY_TITLE, helper_ob.KEY_YEAR };
int[] to = { R.id.tv_title, R.id.tv_year };
//PROBLEM
//cursor = adapter_ob.queryName();
//PROBLEM
//SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to, 1);
/*
moviesList.setAdapter(cursorAdapter);
moviesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
Bundle passdata = new Bundle();
Cursor listCursor = (Cursor) arg0.getItemAtPosition(arg2);
int nameId = listCursor.getInt(listCursor.getColumnIndex(helper_ob.KEY_ID));
passdata.putInt("keyid", nameId);
Intent passIntent = new Intent(MainActivity.this,EditActivity.class);
passIntent.putExtras(passdata);
startActivity(passIntent);
}
});
*/
addbtn.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
Intent addsomemoviesIntent = new Intent(MainActivity.this, AddSomeMovies.class);
startActivity(addsomemoviesIntent);
}
});
}
#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 void InitDataBase() {
MySQLiteHelper sqh = new MySQLiteHelper(this);
SQLiteDatabase sqdb = sqh.getWritableDatabase();
long result = sqh.addMovie("movietitle", "year");
}
}
adapter.java
package com.example.imdbproject;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import android.database.Cursor;
public class adapter {
SQLiteDatabase database_ob;
MySQLiteHelper openHelper_ob;
Context context;
public adapter(Context c)
{
context = c;
}
public adapter openToRead()
{
openHelper_ob = new MySQLiteHelper(context,
MySQLiteHelper.DATABASE_NAME, null, MySQLiteHelper.DATABASE_VERSION);
database_ob = openHelper_ob.getWritableDatabase();
return this;
}
public adapter openToWrite()
{
openHelper_ob = new MySQLiteHelper(context,
MySQLiteHelper.DATABASE_NAME, null, MySQLiteHelper.DATABASE_VERSION);
database_ob = openHelper_ob.getWritableDatabase();
return this;
}
public void Close()
{
database_ob.close();
}
public long insertDetails(String title, String year)
{
ContentValues cv = new ContentValues();
cv.put(MySQLiteHelper.KEY_TITLE, title);
cv.put(MySQLiteHelper.KEY_YEAR, year);
openToWrite();
long val = database_ob.insert(MySQLiteHelper.TABLE_NAME, null, cv);
Close();
return val;
}
public Cursor queryName()
{
String[] cols = { MySQLiteHelper.KEY_ID, MySQLiteHelper.KEY_TITLE,
MySQLiteHelper.KEY_YEAR };
openToWrite();
Cursor c = database_ob.query(MySQLiteHelper.TABLE_NAME, cols, null, null, null, null, null);
return c;
}
public Cursor queryAll(int nameId)
{
String[] cols = { MySQLiteHelper.KEY_ID, MySQLiteHelper.KEY_TITLE, MySQLiteHelper.KEY_YEAR };
openToWrite();
Cursor c = database_ob.query(MySQLiteHelper.TABLE_NAME, cols, MySQLiteHelper.KEY_ID + "=" + nameId, null,null,null,null);
return c;
}
}
MySQLiteHelper
package com.example.imdbproject;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "movie_data.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "movies";
public static final String KEY_ID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_YEAR = "year";
public static final String SCRIPT = "Create table " + TABLE_NAME + " ("
+ KEY_ID + " integer primary key autoincrement, " + KEY_TITLE
+ " text, " + KEY_YEAR + " text);";
public MySQLiteHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public MySQLiteHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
#Override public void onCreate(SQLiteDatabase db)
{
db.execSQL(SCRIPT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE " + TABLE_NAME);
onCreate(db);
}
public long addMovie(String movietitle, String year){
ContentValues cv = new ContentValues();
cv.put(KEY_TITLE, movietitle);
cv.put(KEY_YEAR, year);
SQLiteDatabase sd = getWritableDatabase();
long result = sd.insert(TABLE_NAME, KEY_TITLE, cv);
return result;
}
}
AddSomeMovies
package com.example.imdbproject;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AddSomeMovies extends Activity {
adapter adapter;
MySQLiteHelper helper;
EditText titleEdit, yearEdit;
Button addButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_some_movies);
titleEdit = (EditText)findViewById(R.id.etTitle);
yearEdit = (EditText)findViewById(R.id.etYear);
addButton = (Button)findViewById(R.id.button1);
adapter = new adapter(this);
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
String titleValue = titleEdit.getText().toString();
String yearValue = yearEdit.getText().toString();
long val = adapter.insertDetails(titleValue, yearValue);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_some_movies, menu);
return true;
}
}
activity_main.xml
<RelativeLayout 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"
android:background="#color/black"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/buttonShowAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/buttonTitle"
android:layout_below="#+id/buttonTitle"
android:text="#string/showall"
/>
<Button
android:id="#+id/buttonYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/buttonTitle"
android:layout_alignBottom="#+id/buttonTitle"
android:layout_alignParentRight="true"
android:text="#string/yearsearch"
/>
<Button
android:id="#+id/buttonTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/titlesearch"
/>
<Button
android:id="#+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/buttonShowAll"
android:layout_alignBottom="#+id/buttonShowAll"
android:layout_toRightOf="#+id/buttonShowAll"
android:text="#string/add"
android:onClick="add" />
<Button
android:id="#+id/buttonOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/buttonYear"
android:layout_below="#+id/buttonYear"
android:enabled="false"
android:onClick="ok"
android:text="#string/ok"
android:visibility="invisible" />
<EditText
android:id="#+id/edittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/buttonShowAll"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="#string/searcheditview" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/buttonShowAll"
android:layout_below="#+id/edittext" >
</ListView>
</RelativeLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp" />
</LinearLayout>
SORTED!
At least I think so. Problem disappeared when I changed database version to 2 from 1. So I can guess that it needs more attention now.
try following
public static final String KEY_ID = BaseColumns._ID;
instead of
public static final String KEY_ID = "_id";

only that checkbox are selected those are are in front of us

i have a button to select all check boxes but i have a issue only that check boxes are selected whose are in front of us on scrolling down other check boxes are not selected
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import com.example.callblockerapp.R;
import com.utills.DbHelper;
public class AddFromContacts extends Activity implements OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
ContactsAdapter ma;
ListView lv;
private Button select, btnCancelFromContacts, btnAllFromContacts;
DbHelper db = new DbHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_from_contacts);
getAllContacts(this.getContentResolver());
lv = (ListView) findViewById(R.id.ContactlistView);
ma = new ContactsAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.getSelected);
btnCancelFromContacts = (Button) (findViewById(R.id.btnCancelFromContacts));
btnCancelFromContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// StringBuilder checkedcontacts = new StringBuilder();
String name, phoneNumber;
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
// checkedcontacts.append(name1.get(i).toString());
// checkedcontacts.append("\n");
name = name1.get(i).toString();
phoneNumber = phno1.get(i).toString();
phoneNumber = phoneNumber.replace("-", "");
Log.e("", "Checked Name :- " + name
+ "\nChecked Phone Number :- " + phoneNumber);
db.addBlockedNumber(phoneNumber, name);
finish();
} else {
}
}
// Toast.makeText(AddFromContacts.this, checkedcontacts,
// Toast.LENGTH_LONG).show();
}
});
btnAllFromContacts = (Button) findViewById(R.id.btnAllFromContacts);
btnAllFromContacts.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < lv.getChildCount(); i++) {
ViewGroup item = (ViewGroup) lv.getChildAt(i);
CheckBox checkbox = (CheckBox) item
.findViewById(R.id.checkBox);
// if (!checkbox.isChecked()) {
checkbox.setChecked(true);
btnAllFromContacts.setText("Uncheck All");
// } else if (checkbox.isChecked()) {
// checkbox.setChecked(false);
// btnAllFromContacts.setText("Select All");
// }
}
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class ContactsAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView name, txtNumber;
CheckBox cb;
ContactsAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) AddFromContacts.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.add_from_contacts_row, null);
txtNumber = (TextView) vi.findViewById(R.id.txtNumber);
name = (TextView) vi.findViewById(R.id.name);
cb = (CheckBox) vi.findViewById(R.id.checkBox);
txtNumber.setText("Name :" + name1.get(position));
name.setText("Phone No :" + phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
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) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
xml file add_from_contacts.xml
<RelativeLayout 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"
tools:context=".MainActivity" >
<ListView
android:id="#+id/ContactlistView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffbdbdbd"
android:orientation="horizontal"
android:paddingTop="2.5dip" >
<Button
android:id="#+id/btnAllFromContacts"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="center"
android:text="Select All"
android:textSize="14.0dip" />
<Button
android:id="#+id/getSelected"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="center"
android:text="Add Contact"
android:textAppearance="?android:textAppearanceMedium"
android:textSize="14.0dip" />
<Button
android:id="#+id/btnCancelFromContacts"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="center"
android:text="Cancel"
android:textSize="14.0dip" />
</LinearLayout>
</RelativeLayout>
another xml file add_from_contacts_row.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"
android:orientation="vertical" >
<TextView
android:id="#+id/txtNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/txtNumber" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
May I suggest an easy way to do that? Suppose I have a global variable for class AddFromContacts as,
public static boolean checked=false;
now, inside the button click (Button to select/deselect all), leave the loop you wrote as it is. Include the following.
if(checked)
checked=false;
else
checked=true;
Then inside Adapter getView(),
cb.setChecked(AddFromContacts.checked);
Eg: worked for me
public class MainActivity extends Activity {
ListView lv;
Button b1;
boolean checked=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.listView1);
b1=(Button) findViewById(R.id.button1);
Myadapter adapter=new Myadapter();
lv.setAdapter(adapter);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(checked)
checked=false;
else
checked=true;
for (int i = 0; i < lv.getChildCount(); i++) {
ViewGroup item = (ViewGroup) lv.getChildAt(i);
CheckBox checkbox = (CheckBox) item
.findViewById(R.id.checkBox1);
checkbox.setChecked(checked);
}
}
});
}
class Myadapter extends BaseAdapter{
CheckBox cb;
LayoutInflater mInflater;
public Myadapter() {
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 15;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.item, null);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
cb.setTag(position);
cb.setChecked(checked);
return vi;
}
}
}
Also, I can see a method public void setChecked(int position, boolean isChecked). If you meant to call this, change the code to setChecked(position,mCheckStates.get(position, false));

Categories

Resources