I have a prefilled DB in Assets, that will be copied and opened after App start.
I have a activity who Displays the Column Name with rawQuery
Cursor c = database.rawQuery("SELECT _id, Name from DB
ORDER BY Name ASC", null);
ArrayList<String> values = new ArrayList<String>();
while (c.moveToNext()) {
values.add(c.getString(c.getColumnIndex("Name")));
}
c.close();
and starts onItemClick a new intent who Displays the other colums (new activity get "Name" variable with i.putExtra)
private void getSQLData() {
Bundle extras = getIntent().getExtras();
String Name = extras.getString("Name");
DataBaseHelper myDbHelper = new DataBaseHelper(null);
myDbHelper = new DataBaseHelper(this);
SQLiteDatabase database = myDbHelper.getWritableDatabase();
ListView lv = (ListView)findViewById(R.id.listView1);
Cursor c = database.rawQuery("SELECT * from DB WHERE Name='"+Name+"' ORDER BY Name ASC", null);
ArrayList<String> values = new ArrayList<String>();
while (c.moveToNext()) {
values.add(c.getString(c.getColumnIndex("Name")));
values.add(this.getString(R.string.x) + (c.getString(c.getColumnIndex("x"))+" "+this.getString(R.string.x)+":"));
values.add((c.getString(c.getColumnIndex("y")) + this.getString(R.string.y) + " " + this.getString(R.string.y)));
}
c.close();
ArrayAdapter<String> NamenDetails = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
values);
}
lv.setAdapter(NamenDetails); }
I get all SQL datas I need, but in the Default View.
But I Need it customized like for exmaple :
I tried many many tutorials with custom listview and simplecursoradapter but I think all
be defeated by the ArrayListString.
I hope anyone can help me I get frustrated..
Thanks!
This is an example of listview with its single row having two textviews. This the thing you wanted:
CustomListView.java:
package com.customlistview;
import java.util.ArrayList;
import resources.PlacesListAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class CustomListView extends Activity {
/** Called when the activity is first created. */
private ArrayList<String> mPlacesData1 = new ArrayList<String>();
private ArrayList<String> mPlacesData2 = new ArrayList<String>();
PlacesListAdapter mPLAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlacesData1.clear();
mPlacesData2.clear();
mPlacesData1.add("ICD1");
mPlacesData2.add("SubTitle1");
mPlacesData1.add("ICD2");
mPlacesData2.add("SubTitle2");
mPlacesData1.add("ICD3");
mPlacesData2.add("SubTitle3");
mPlacesData1.add("ICD4");
mPlacesData2.add("SubTitle4");
mPlacesData1.add("ICD5");
mPlacesData2.add("SubTitle5");
mPlacesData1.add("ICD6");
mPlacesData2.add("SubTitle6");
mPlacesData1.add("ICD7");
mPlacesData2.add("SubTitle7");
mPlacesData1.add("ICD8");
mPlacesData2.add("SubTitle8");
ListView listView = (ListView) findViewById(R.id.listview);
mPLAdapter = new PlacesListAdapter(CustomListView.this, mPlacesData1, mPlacesData2);
listView.setAdapter(mPLAdapter);
}
}
PlaceListAdapter.java:
package resources;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.customlistview.R;
public class PlacesListAdapter extends BaseAdapter {
// private Context mContext;
private LayoutInflater mInflater;
private ArrayList<String> AL_id_text = new ArrayList<String>();
private ArrayList<String> AL_text = new ArrayList<String>();
public PlacesListAdapter(Context c, ArrayList<String> AL_name_time,
ArrayList<String> AL_name_time1) {
mInflater = LayoutInflater.from(c);
// mContext = c;
this.AL_id_text = AL_name_time;
this.AL_text = AL_name_time1;
}
public int getCount() {
return AL_id_text.size();
}
public Object getItem(int position) {
return AL_id_text.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.place_row, null);
holder = new ViewHolder();
holder.txt_maintext = (TextView) convertView
.findViewById(R.id.txt_maintext);
holder.txt_mtext = (TextView) convertView
.findViewById(R.id.txt_mtext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt_maintext.setText(AL_id_text.get(position));
holder.txt_mtext.setText(AL_text.get(position));
return convertView;
}
static class ViewHolder {
TextView txt_maintext;
TextView txt_mtext;
}
}
activity_main.xml:
<?xml version="1.0" encoding="UTF-8"?>
-<LinearLayout android:orientation="vertical" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <ListView android:layout_height="match_parent" android:layout_width="match_parent" android:id="#+id/listview"> </ListView> </LinearLayout>
place_row.xml:
<?xml version="1.0" encoding="UTF-8"?>
-<LinearLayout android:orientation="vertical" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> -<LinearLayout android:orientation="vertical" android:layout_height="70dip" android:layout_width="match_parent" android:id="#+id/lin_main"> <TextView android:layout_height="20dip" android:layout_width="fill_parent" android:id="#+id/txt_maintext" android:singleLine="true" android:paddingRight="5dip" android:paddingLeft="5dip" android:layout_marginTop="5dip" android:textColor="#fff"/> <TextView android:layout_height="20dip" android:layout_width="fill_parent" android:id="#+id/txt_mtext" android:singleLine="true" android:paddingRight="5dip" android:paddingLeft="5dip" android:layout_marginTop="15dip" android:textColor="#fff"/> </LinearLayout> <ImageView android:layout_height="3dip" android:layout_width="match_parent" android:background="#0000ff"/> </LinearLayout>
This is an example. You can make necessary edits to achieve what you want.
Related
This is my class and this is where i display the data to a list adaptor R.id.listView1 so all i need is a custom adaptor please i'm new to android
and all other tutorials are out of my league.
This is just a small help i require form the community as this help me a great amount.
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class View_Data extends AppCompatActivity {
public ArrayList<String> datax = new ArrayList<String>(); //used to store data from db
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_data);
final String LOG_TAG = View_Data.class.getSimpleName();
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/AABOHI.TTF"); // this is the custom font i want to use
try {
String table = "questions";
String[] columnsToReturn = {"question_id", "question", "def_font"};
SQLiteDatabase mydatabase = openOrCreateDatabase("Data",MODE_PRIVATE,null);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/AABOHI.TTF");
Cursor dbCursor = mydatabase.query(table, null,null, null, null, null, null);
dbCursor.moveToFirst();
String temp ;
int i = 0;
ListView listView1 = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, datax);
listView1.setAdapter(adapter);
while (!dbCursor.isAfterLast()) {
Log.v(LOG_TAG, String.valueOf(dbCursor.getString(0)));
Log.v(LOG_TAG, String.valueOf(dbCursor.getString(1)));
temp = " Question : " + String.valueOf(dbCursor.getString(1)) ;//This is what i want in a custom font
datax.add(temp);
dbCursor.moveToNext();
i++;
}
dbCursor.close();
for (String row : datax) {
Log.v(LOG_TAG, row);
}
} catch (Exception e) {
Log.v(LOG_TAG, e.toString());
}
ListView listView1 = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, datax);
listView1.setAdapter(adapter);
}
}
You can go for base adapter for this type of requirement wherein you can have the facility to modify a lot of things. To know and implement base adapter go through the links :
How to customize listview using baseadapter
http://abhiandroid.com/ui/baseadapter-tutorial-example.html
You can easily customize the base adapter for your required data and font.
Create a base adapter as below :
public class CustomAdapter extends BaseAdapter {
Context context;
ArrayList<String> arrayList;
LayoutInflater inflter;
Typeface font;
public CustomAdapter(Context applicationContext, ArrayList<String> arrayList) {
this.context = applicationContext;
this.arrayList = arrayList;
inflter = (LayoutInflater.from(applicationContext));
font = Typeface.createFromAsset(context.getAssets(), "fonts/Questrial-Regular.ttf");
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_item, null);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText(arrayList.get(i));
tv.setTypeface(font);
return view;
}
}
Main activity
public class MainActivity extends AppCompatActivity {
ArrayList<String> simpleStringArrayList;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleStringArrayList = new ArrayList<>();
simpleStringArrayList.add("aaa");
simpleStringArrayList.add("bbb");
simpleStringArrayList.add("ccc");
simpleStringArrayList.add("ddd");
simpleStringArrayList.add("eee");
simpleStringArrayList.add("fff");
simpleStringArrayList.add("ggg");
listView = (ListView) findViewById(R.id.listView);
listView= (ListView) findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter(this, simpleStringArrayList);
listView.setAdapter(customAdapter);
}
}
activity_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<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: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="com.example.dell1.myapplication.MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
I'm pretty newbie to Android development (2 days old).
I intend to create an app that list all the currently installed applications in the device and a column beside each of those results showing the permissions granted. I understand that conventionally a listView has 1 column , how do I make another column ?
I'm open to other ideas as well (like perhaps another intent when i click the installed application name ?)
Below is my code thus far which shows all installed applications :
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
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.TextSwitcher;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class PopAnalysis extends Activity{
ListView appList;
private TextSwitcher mSwitcher;
TextView myText;
private ArrayList results = new ArrayList();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupanalysis);
appList = (ListView)findViewById(R.id.listViewApp);
PackageManager pm = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN,null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ArrayList<ResolveInfo> list = (ArrayList<ResolveInfo>) pm.queryIntentActivities(intent, PackageManager.PERMISSION_GRANTED);
for (ResolveInfo rInfo : list) {
results.add(rInfo.activityInfo.applicationInfo.loadLabel(pm).toString());
System.out.println(rInfo.activityInfo.applicationInfo.loadLabel(pm).toString());
}
appList.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, results));
appList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemposition = position;
String value = (String) appList.getItemAtPosition(position);
}
});
}
}
Following are my XML codes :
<?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">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listViewApp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="56dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textViewAnalysis"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/list_item_appname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textAppearance="#android:style/TextAppearance.Medium" />
<TextView
android:id="#+id/list_item_apppermissions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</RelativeLayout>
Firstly you need load apps list and permission for every apps. I do it inside Activity.onCreate to simplify example. The better way to do it inside AsyncTask
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final PackageManager packageManager = getPackageManager();
final List<Pair<String, List<String>>> appsWithPermission = new ArrayList<>();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
for (ResolveInfo info : apps) {
final ApplicationInfo applicationInfo = info.activityInfo.applicationInfo;
final String appName = (String) applicationInfo.loadLabel(packageManager);
final List<String> permissions = new ArrayList<>();
if (appName != null) {
try {
final PackageInfo packageInfo = packageManager.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS);
final String[] requestedPermissions = packageInfo.requestedPermissions;
if (requestedPermissions != null) {
permissions.addAll(Arrays.asList(requestedPermissions));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
appsWithPermission.add(new Pair<>(appName, permissions));
}
final ListView listView = (ListView) findViewById(R.id.list_view);
final AppsAdapter appsAdapter = new AppsAdapter(this, appsWithPermission);
listView.setAdapter(appsAdapter);
}
}
Secondly you need xml layout list_item.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/list_item_appname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textAppearance="#android:style/TextAppearance.Medium" />
<TextView
android:id="#+id/list_item_apppermissions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
and finally AppsAdapter.java
public class AppsAdapter extends BaseAdapter {
private final Context mContext;
private List<Pair<String, List<String>>> mAppsWithPermission;
public AppsAdapter(Context context, List<Pair<String, List<String>>> appsWithPermission) {
mContext = context;
mAppsWithPermission = appsWithPermission;
}
static class ViewHolder {
public TextView appName;
public TextView appPermissions;
}
#Override
public int getCount() {
return mAppsWithPermission.size();
}
#Override
public Object getItem(int position) {
return mAppsWithPermission.get(position);
}
#Override
public long getItemId(int position) {
return mAppsWithPermission.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.appName = (TextView) convertView.findViewById(R.id.list_item_appname);
holder.appPermissions = (TextView) convertView.findViewById(R.id.list_item_apppermissions);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Pair<String, List<String>> item = mAppsWithPermission.get(position);
holder.appName.setText(item.first);
holder.appPermissions.setText(item.second.toString());
return convertView;
}
}
I see you've already figured out how to get a list of all installed applications and their respective permissions, which is good. In order to make a ListView with multiple columns, though, you'll need to implement a ListViewAdapter.
A really great resource for figuring out how to do this can be found here.
If you're confused about anything on that link, or something doesn't work, let me know.
Code:
PopAnalysis.java
public class PopAnalysis extends Activity {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
ListView appList;
private TextSwitcher mSwitcher;
TextView myText;
private ArrayList results = new ArrayList();
private ArrayList<HashMap<String, String>> list;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupanalysis);
appList = (ListView)findViewById(R.id.listViewApp);
HashMap<String,String> t1 = new HashMap<String, String>();
t1.put(FIRST_COLUMN, "App 1");
t1.put(SECOND_COLUMN, "Permission 1");
list.add(t1);
ListViewAdapter adapter = new ListViewAdapter(this, list);
listView.setAdapter(adapter);
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
public ArrayList<HashMap<String, String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.column_row_layout, null);
txtFirst=(TextView) convertView.findViewById(R.id.application);
txtSecond=(TextView) convertView.findViewById(R.id.permissions);
}
HashMap<String, String> map=list.get(position);
txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
return convertView;
}
}
column_row_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView android:id="#+id/application"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:textStyle="bold" />
<TextView android:id="#+id/permissions"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"/>
</LinearLayout>
In PopAnalysis.java I added only one entry to simply show how it's done. Certainly you shouldn't have any issues implementing the data you want into it.
Instead of 2 column listview , you can also try ExpandableListView. Clicking on the item with expand a detail view just below to it.
detail view will contain the permissions of that app.
Expandable Listview Tutorial
BTW, there is no way in SDK's listview to have multiple column. What you can do is to have a pseudo-multicolumn list view like using multiple textview(or other kind of view) in the same row. In that case you will need to make a custom adapter for your list view and a custom row layout file.
If you really want to have something multi-column, then either 3rd party libraries or TableLayout is your only option.
TableLayout tutorial
to make two column listview you have to implement custom listview. please read this link
in program_list.xml instead of imageview take textview it will resolve your problem.
I want to display values from my COLUMN_INGRIDIENTS column from my db to a TextView in another activity when a certain data on list in my Main activity is clicked.
Main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/myListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/recipeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
Main.java
package com.example.viewer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends Activity {
public final static String TAG_INGRIDIENTS="com.example.getlistfromdb.INGRIDIENTS";
private recipelistHelper dbrecipelistHelper = null;
private Cursor ourCursor = null;
private recipeAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView myListView = (ListView) findViewById(R.id.myListView);
dbrecipelistHelper = new recipelistHelper(this);
dbrecipelistHelper.createDatabase();
dbrecipelistHelper.openDatabase();
ourCursor=dbrecipelistHelper.getCursor();
startManagingCursor(ourCursor);
adapter = new recipeAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent i=new Intent(Main.this, Activity2.class);
String ingridients = null;
i.putExtra(TAG_INGRIDIENTS,ingridients);
startActivity(i);
}
};
class recipeAdapter extends CursorAdapter {
recipeAdapter(Cursor c){
super(Main.this, c);
}
#Override
public void bindView (View row, Context ctxt, Cursor c)
{
recipeHolder holder = (recipeHolder)row.getTag();
holder.populateFrom(c, dbrecipelistHelper);
}
#Override
public View newView(Context ctxt, Cursor c, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row=inflater.inflate(R.layout.list, parent, false);
recipeHolder holder = new recipeHolder(row);
row.setTag(holder);
return(row);
}
}
static class recipeHolder {
private TextView name=null;
recipeHolder(View row){
name=(TextView)row.findViewById(R.id.recipeText);
}
void populateFrom(Cursor c, recipelistHelper r){
name.setText(r.getName(c));
}
}
}
Activity2.java
package com.example.viewer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Activity2 extends Activity {
String ingridients = null;
String procedure = null;
private TextView txtIngridients = null;
private TextView txtProcedure = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
ingridients=this.getIntent().getStringExtra(Main.TAG_INGRIDIENTS);
//procedure=this.getIntent().getStringExtra(Main.TAG_PROCEDURE);
txtIngridients=(TextView)findViewById(R.id.ingridientText);
//txtProcedure=(TextView)findViewById(R.id.procedureText);
txtIngridients.setText(ingridients);
//txtProcedure.setText(procedure);
}
}
view.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/ingridientText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:text="A" />
</RelativeLayout>
Use adapter.getItem to get cursor of selected row in ListView :
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Cursor selectedCursor=(Cursor)adapter.getItem(position);
// get ingridients coulmn value from selectedCursor
selectedCursor.moveToPosition(position);
String ingridients = dbrecipelistHelper.getName(selectedCursor);
// your code here
}
In your onItemClickListener you assign null to your string:
String ingridients = null;
and pass this String to your next Activity. This will be null. You have to fetch your data before you initialize your ingridients variable and set it to the desired String.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to make the contact list with checkboxs. So I have to select the contacts to send a group message ; I tried this code but it doesn't work...
What can you suggest to me what to do further to get the contact list.
MainActivity.java
package com.example.cont1;
import java.util.ArrayList;
import com.example.cont.MainActivity;
import com.example.listo1.Demo;
import com.example.listo1.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
StringBuilder sb= new StringBuilder();
String str;
ListView tx;
private Contact selectedAdapter;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
class ast extends AsyncTask<String, Void, String> {
String name, phone;
ProgressDialog pd;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "", "loading");
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.cancel();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, str);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//textDetail.setText(sb);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
String phone = null;
if (cur.getCount() > 0) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
sb.append("\n " + name + "\n" + phone);
sb.append("\n............................\n");
str=sb.toString();
}
phones.close();
}
return null;
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, String.valueOf(getListView().getCheckedItemCount()), Toast.LENGTH_LONG).show();
return true;
}
}
Contact.java
package com.example.cont1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class Contact extends ArrayAdapter {
private MainActivity list;
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
private Context context;
private String[] values;
public Contact(Context context, String[] values) {
super(context, R.layout.activity_main, values);
this.context = context;
this.values = values;
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.activity_main, null);
// get text view
TextView label = (TextView)v.findViewById(R.id.textView1);
ImageView btn=(ImageView)v.findViewById(R.id.icon);
if (convertView == null) {
v = vi.inflate(R.layout.activity_main, parent, false);
}
else
v = convertView;
TextView text1 = (TextView) v.findViewById(R.id.textView1);
text1.setText(values[position]);
LinearLayout layout_item = (LinearLayout) v.findViewById(R.id.linear);
//Set the background and text color
if (position % 2 == 0) {
layout_item.setBackgroundColor(context.getResources().getColor(R.color.black));
text1.setTextColor(context.getResources().getColor(R.color.white));
} else {
layout_item.setBackgroundColor(context.getResources().getColor(R.color.white));
text1.setTextColor(context.getResources().getColor(R.color.black));
}
return v;
}
}
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linear"
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:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"/>
<ImageView
android:id="#+id/icon"
android:layout_width="22px"
android:layout_height="22px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px">
</ImageView>
</LinearLayout>
</ScrollView>
</LinearLayout>
rowLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</LinearLayout>
It appears that it's quite complicated to do it with an Async Task but here is a Snippet coming from https://stackoverflow.com/a/17878191/2545832 but a bit more complete (but still quite simple) which is working (I tested it):
Main Activity:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView lvCallList;
ProgressDialog pd;
ArrayList<String> aa = new ArrayList<String>();
ArrayList<String> num= new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvCallList = (ListView) findViewById(R.id.list);
new AsyncTask<Void, Void, Void>()
{
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(MainActivity.this,
"Loading..", "Please Wait", true, false);
}// End of onPreExecute method
#Override
protected Void doInBackground(Void... params)
{
getContacts();
return null;
}// End of doInBackground method
#Override
protected void onPostExecute(Void result)
{
pd.dismiss();
CustomAdapter cus = new CustomAdapter(MainActivity.this);
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
lvCallList.setAdapter(cus);
}//End of onPostExecute method
}.execute((Void[]) null);
}
private void getContacts()
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
aa.add(name);
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id},
null);
while (pCur.moveToNext())
{
String phoneNumber = pCur.getString(pCur.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
num.add(phoneNumber);
}
pCur.close();
}
}
}
}
public class CustomAdapter extends BaseAdapter
{
/*
* Variables Declaration section
*/
private Context mContext;
public CustomAdapter(Context context)
{
mContext = context;
}//End of CustomAdapter constructor
public int getCount()
{
return aa.size();
}//End of getCount method
public Object getItem(int position)
{
return position;
}//End of getItem method
public long getItemId(int position)
{
return position;
}//End of getItemId method
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
final int pos = position;
if (convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.display_contact, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.textView1);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.textView2);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}//End of if condition
else
{
holder = (ViewHolder) convertView.getTag();
}//End of else
holder.checkbox.setId(position);
holder.textviewName.setId(position);
holder.textviewNumber.setId(position);
holder.textviewName.setText(aa.get(position));
holder.textviewNumber.setText("No. "+num.get(position));
holder.id = position;
return convertView;
}//End of getView method
}//End of CustomAdapter instance inner class
static class ViewHolder
{
TextView textviewName;
TextView textviewNumber;
CheckBox checkbox;
int id;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list">
</ListView>
display_contact.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" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"/>
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox1"/>
</LinearLayout>
I saw in your code that you were able to select many items so it mustn't be a problem for you to select many contacts from this list. You've two options : listener on each checkboxes or a long click listener on the list.
Good luck :)
i have android application that display a listview that extends Base Adapter to get image and text.
now i want to add a header section for this list view how to do it ? can anyone help me ???
this is how the list view is shown
what i wnat is that before the first item display a header and before the last item to display a header.
activity_group_list.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: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=".GroupList" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
row_list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#drawable/algeria_flag" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageView1"
android:ems="10"
android:text="text" />
</RelativeLayout>
ItemDetails.java
package com.devleb.expandablelistdemo3;
public class ItemDetails {
String Name;
int image;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
}
CustomAdapter.java
package com.devleb.expandablelistdemo3;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter {
private static ArrayList<ItemDetails> itemDetailsarrayList;
LayoutInflater layoutInflater;
String[] teamName;
int[] teamFlag;
Context context;
public CustomAdapter(ArrayList<ItemDetails> result, Context c) {
itemDetailsarrayList = result;
context = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemDetailsarrayList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return itemDetailsarrayList.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = layoutInflater.inflate(R.layout.row_list_group, parent,
false);
TextView txt = (TextView) row.findViewById(R.id.textView1);
ImageView imgv = (ImageView) row.findViewById(R.id.imageView1);
txt.setText(itemDetailsarrayList.get(position).getName());
imgv.setImageResource(itemDetailsarrayList.get(position).getImage());
return row;
}
}
GroupList.java
package com.devleb.expandablelistdemo3;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.ClipData.Item;
import android.view.Menu;
import android.widget.ListView;
public class GroupList extends Activity {
int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag,
R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain,
R.drawable.netherlands_flag, R.drawable.czech_republic_flag,
R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress,
R.drawable.cote_divoire_flag, R.drawable.japan,
R.drawable.uruguay_flag, R.drawable.costa_rica_flag,
R.drawable.england_flag, R.drawable.italy_flag,
R.drawable.switzerland, R.drawable.ecuador_flag,
R.drawable.france_flag, R.drawable.honduras_flag,
R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag,
R.drawable.nigeria_flag, R.drawable.germany_flag,
R.drawable.portugal, R.drawable.ghana_flag,
R.drawable.united_states_flag, R.drawable.belgium_flag,
R.drawable.algeria_flag, R.drawable.russia_flag,
R.drawable.korea_flag };
String[] name = { "BRA", "CRO", "MEX", "CMR", "ESP", "NED", "CHI", "AUS",
"COL", "GRE", "CIV", "JPN", "URU", "CRC", "ENG", "ITA", "SUI",
"ECU", "FRA", "HON", "ARG", "BIH", "IRN", "NGA", "GER", "POR",
"GHA", "USA", "BEL", "ALG", "RUS", "KOR" };
ItemDetails item_details;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_list);
ArrayList<ItemDetails> result = getList();
ListView lv = (ListView) findViewById(R.id.list);
lv.setAdapter(new CustomAdapter(result, getApplicationContext()));
}
private ArrayList<ItemDetails> getList() {
ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();
for (int i = 0; i <32; i++) {
item_details = new ItemDetails();
item_details.setName(name[i]);
item_details.setImage(img[i]);
results.add(item_details);
}
return results;
}
added section
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_list);
TextView txtSection = (TextView)findViewById(R.id.textSeparator);
ArrayList<ItemDetails> result = getList();
lv = (ListView) findViewById(R.id.list);
lv.addHeaderView(txtSection);
lv.setAdapter(new CustomAdapter(result, getApplicationContext()));
}
private ArrayList<ItemDetails> getList() {
ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();
for (int i = 0; i <4; i++) {
item_details = new ItemDetails();
View layout_section = getLayoutInflater().inflate(R.layout.activity_group_section_list, null);
lv.addHeaderView(layout_section );
item_details.setName(name[i]);
item_details.setImage(img[i]);
results.add(item_details);
}
return results;
}
}
log cat
03-29 08:30:34.271: E/AndroidRuntime(2900): Caused by: java.lang.NullPointerException
03-29 08:30:34.271: E/AndroidRuntime(2900): at com.devleb.expandablelistdemo3.GroupList.getList(GroupList.java:59)
In your row_list_group.xml, create a header layout and set its visibility to gone. Then set it to visible when you need to add a header.
Or you can try what Nickolai has suggested:
This way you need to create a layout and add to the listview at the runtime in the list adapter getView method.
In GroupList in onCreate method just add the following line:
ListView lv = (ListView) findViewById(R.id.list);
lv.addHeaderView(<place your header view here>);
addHeaderView expects to get View object. So, you can place header using two ways:
//Programmatically create button (or other view, that you need) and place it:
Button b = new Button(this);
lv.addHeaderView(b);
// Create xml layout, inflate it and place into listview as header view
View yourLayout = getLayoutInflater().inflate(R.layout.your_view_layout, null);
lv.addHeaderView(yourLayout );