How to get ID of Button that was generated from SQLite - java

I used SQLiteAssetHelper. I connected SQLite database to connect to my populate_list.xml. Buttons gets sub_products column from my table. I am trying to get the ID of button. When I used ViewFindById(name_of_button). It returns null. I am thinking maybe I need refresh but I don't exactly know how to do that.
This is my CoreOpenDB.class. This is not Mainactivity
public class CoreOpenDB extends ListActivity {
private Cursor products;
private MyDatabase db;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
String value = "test"; // or other values
if(b != null)
value = b.getString("key");
db = new MyDatabase(this);
products = db.getProducts(value);
ListAdapter adapter = new SimpleCursorAdapter(this,
R.layout.populate_list,
products,
new String[] {"sub_products"},
new int[] {R.id.text_list});
getListView().setAdapter(adapter)
}
This is populate_list.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" >
<Button
android:id="#+id/text_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Sample Product"
android:padding="25px"
android:textColor="#333"
android:textSize="38dp" />
</LinearLayout>
And this is the result
I need to get id's of each item. Thank you .

Related

Populate ListView with List of Objects

I have list if twitter statuses and I want to populate it in a listview
public class TwitterTimeline extends Activity {
List<Status> statuses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_timeline);
setTitle("Timeline");
ListView listview = (ListView) findViewById(R.id.listView);
Bundle b = this.getIntent().getExtras();
if (b != null) {
MyStatuses myStatuses = (MyStatuses) b.getSerializable("statuses");
statuses = myStatuses.statuses;
for (Status st : statuses) {// this prints all the status on the catlog
Log.d("Abharthan : ", st.getUser().getScreenName()+ ":" + st.getText());
}
ArrayAdapter<MyStatuses> adapter = new ArrayAdapter<MyStatuses>(this,
android.R.layout.simple_list_item_1, statuses);// this line is giving error
listview.setAdapter(adapter);
}
}
Here MyStatus Class is:
import java.io.Serializable;
import java.util.List;
import twitter4j.Status;
public class MyStatuses implements Serializable {
List<Status> statuses;
}
The layout file containing list view is android_twitter_timeline.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.android.HomeWork3.TwitterTimeline">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
How can I populate my listview with twitter statuses using ArrayAdapter or any other method.
Basically, you will have to create an ArrayAdapter with your own data type. Inside, the adapter, you will populate the view for each row in the ListView.
Then, set that adapter to your ListView.
Please check out this guide Using an ArrayAdapter with ListView. And you will got to use "Using a Custom ArrayAdapter"
You can use a ArrayAdapter or BaseAdapter, here is a example with code, HERE
Please change the ArrayAdapter from MyStatuses to Status

Clickable text, new Intent, sqlite

I have a database and a method, which can get all my info from my database to a TextView. It shows only the Title of each row, there are more columns, which I want to show on new Intent when I click on a Title. My question is, how can I make each title clickable and if clicked it opens up a new intent with the relevant information(need to pass the id)? Many thanks. :)
My History Activity -
public class HistoryActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.history_layout);
final LinearLayout linearLayoutBackground = (LinearLayout) findViewById(R.id.MainLinearLayout);
TextView tv = (TextView) findViewById(R.id.tvHistory);
DataBaseHelper DataBaseHelper = new DataBaseHelper(this);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
int backgroundImages[] = {R.drawable.background1,
R.drawable.background2};
final Drawable backgroundImage = getResources().getDrawable(
backgroundImages[intValue]);
linearLayoutBackground.setBackgroundDrawable(backgroundImage);
DataBaseHelper.open();
String HistoryData = DataBaseHelper.getListData();
DataBaseHelper.closee();
tv.setText(HistoryData);
}
}
getListData method -
public String getListData() {
open();
Cursor c = myDataBase.query(TABLE_NAME1, columns, WHATTODONOW_COLUMN_ID, null, null, null, null);
String result = "";
int iTitle = c.getColumnIndex(WHATTODONOW_COLUMN_TITLE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iTitle) + "\n";
}
return result;
}
HistoryLayout -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MainLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="10dp">>
<TableRow>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:text="All the things you have already done!"
android:textSize="20dp"
android:textStyle="bold">
</TextView>
</TableRow>
</TableLayout>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp">
<TextView
android:id="#+id/tvHistory"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="get info from db"
android:paddingBottom="10dp"
android:textSize="25dp">
</TextView>
</ScrollView>
</LinearLayout>
There are two ways to go from my experience. First instead of using a ListView you look at ExpandableListView, which might accomplish what you want in one activity instead of having to start another intent.
Second, if you want to stick with the 2 intent design you have to pass some data from the current intent to the new one, you could do something like:
Intent i = new Intent(yourcurrentactivity.this, yournewactivity.class);
// following line is an example of passing data to the new intent.
i.putExtra(getString(R.string.str_selecteddialog), "1");
startActivity(i);
this.finish();
In the new intent that you have started in the onCreate you need to retrieve the data from the bundle:
Bundle extras = getIntent().getExtras();
if (extras != null) {
// Log.i(TAG, " 022:... we got some extras");
str_selecteddialog = getIntent().getStringExtra(getString(R.string.str_selecteddialog));
There are different types of put and get 'Extras' dependent on variable types. Now you have to decide: Do I get all the data from the cursor and pass it to this new intent or Do I just pass the row id column, typically '_id' and query it in this activity.
Hope this helps.

Android listview with multiple controls

I am new to android. I am developing an application in which there is a list view of students with edit and delete buttons. Like
STUDENT LIST
[ABC] [edit] [delete]
[DEF] [edit] [delete]
With this code im able to list student details in a <Textview>
public class DataBaseDemoActivity extends ListActivity {
/** Called when the activity is first created. */
SQLiteDatabase db;
Button btnInsert;
ArrayAdapter<String> students;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
db=openOrCreateDatabase("StudentDB",SQLiteDatabase.CREATE_IF_NECESSARY,null);
Cursor c=db.rawQuery("SELECT * FROM temp",null);
String[] students = new String[c.getCount()];
if (c.moveToFirst())
{
for (int i = 0; i < c.getCount(); i++)
{
students[i] = c.getString(0).toString()+" "+c.getString(1).toString();
c.moveToNext();
}
}
c.close();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, students));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}catch(SQLException e)
{
}
}
}
I need to store the id of the record with in the list view so that when i click on the edit or delete button, i'll have to find out the id and make changes on the DB. How can i set values to two fields say <TextView>[show details] and <EditText>[visibility: insisible - to save id of the record]. I am able to get the details to the <TextView> using the above code. Any suggestion will be appreciated.
UPDATE :
Layout i am using
<?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="horizontal"
>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:inputType="text"
android:onClick="showInfo"
/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="230dip"
android:layout_height="wrap_content"
android:textSize="16sp"
android:id="#+id/studentInfo" >
</TextView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/action"
android:onClick="showInfo"
/>
</LinearLayout>
You can get the Id within cursor data fetch loop, use any HashMap<id,String> collection for it and store id along with data (text).
As per your requirement, I suggest you to use SimpleCursorAdapter instead of ArrayAdapter with ListView.
So you can manage easily your database records with your list and also get the all information related to database for particular record when List Item clicked.
Look at SimpleCursorAdapters and ListViews
Creating a custom CursorAdapter for Android
after this line..
students[i] = c.getString(0).toString()+" "+c.getString(1).toString();
student_ids[i]=Integer.parseInt(//get the id... )
//and you dont need to put it in invisible edittext...
in onclick method you will get integer "position"..and get tha value in students_ids[] at that position..
int id=students_ids[position];

How to create an ListView without ListActivity

Someone could tell me how can I create a ListView without using a ListActivity?
I need to put in my layout several other views, and I wish the layout was not fully occupied by the ListView. It must be part of the layout, not the entire layout. I want to create a normal Activity.
Code snippet:
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.savings);
//...
ListView lvPoupanca = (ListView)this.findViewById(R.id.lvPoupanca);
// the adapter
TestRepository repo = new TestRepository(this);
Cursor c = repo.getCursor();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, c, new String[]{"Nome", "ValorAtual"}, new int[] {R.id.tvNome, R.id.tvValorTotal});
lvPoupancas.setAdapter(adapter);
// ...
}
Edit:
The saving.xml file:
<?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" >
<ListView
android:id="#+id/lvPoupancas"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
Hope somebody can help me.
Thanks and sorry about my bad english.
Like with any other View in any Activity...
ListView l = new ListView(this);
// OR
ListView l = (ListView) findViewById(R.id...);
...
l.setAdapter(...);
// If using first way: setContentView(l);
For example
I have replied to a similar question before. But that was in a different context. So, I'm putting some reference code here. It will help you to fix the issue.
public class ListandtextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] str = {"ONE","TWO","THREE"};
final ListView lv = (ListView) findViewById(R.id.listView1);
final TextView tv = (TextView)findViewById(R.id.tv1);
ArrayAdapter<Object> adapt = new ArrayAdapter<Object>(getApplicationContext(), android.R.layout.simple_list_item_1, str);
lv.setAdapter(adapt);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
tv.setText("You Clicked Something");
}
});
}
}
And the XML is
<?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" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" android:textSize="20dip"/>
</LinearLayout>
By the way, before asking questions, collect as much information as possible for others to help you. If it does not work, it will be better to put the error log in the question rather than just saying it does not work.
Don't Extend ListActivity then. Extend an Activity and in onCreate() put the following code as per your requirement.
setContentView(R.layout.ur_xml);
Listview list = (ListView)findViewById(R.id.lvPoupancas);
list.setAdapter(your Adapter);

Populating ListView from Cursor

I've been looking on here for quite some time and I cannot find an answer to my problem. There are many similar issues. But I haven't been able to come up with any solution that works. I am very new to android/java programming so I really appreciate any help.
Background: I have an activity screen that contains 2 listviews. The first listview contains a list of names coming from a database. (This is working correctly).
Then when a user clicks on one of the names in the list, the onItemClick event fires and builds a cursor from all the data associated from the name. (Have verified that I am getting a cursor with valid results).
Problem: When I try to put the resulting cursor into a SimpleCursorAdapter to set my listadpter to, I am receiving no errors, but I'm not getting anything displayed to the screen.
I have data coming from a SQLite database. It is simply 4 columms with X number of rows. All I want to do is display everything on the list and then maybe do some analysis.
Here is my code:
public class TipCalculator_w_Database extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.databaseinfoscreen);
ListView lv1 = null;
lv1 = (ListView) findViewById (R.id.List1);
final ListView lv2;
lv2 = (ListView) findViewById (R.id.List2);
final DataBase showData = new DataBase(getApplicationContext());
showData.open();
Cursor NameList = showData.GetAllNames();
startManagingCursor(NameList);
// Create an ArrayAdapter, that will actually make the Strings above
// appear in the ListView
int i = NameList.getCount();
String[] FinalString = new String[i];
int j = 0;
while (NameList.moveToNext()) {
FinalString[j] = NameList.getString(0);
j++;
}
if(j != 0)
{
lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_gallery_item, FinalString));
}
NameList.close();
showData.close();
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selectedName = ((TextView) view).getText().toString();
Context ctx= parent.getContext();
final DataBase showData = new DataBase(getApplicationContext());
showData.open();
final String[] columns = new String[] { showData.KEY_ROWID, showData.KEY_NAME, showData.KEY_BILL, showData.KEY_TIP};
final int[] to = new int[] { R.id.ID_list, R.id.Name_list, R.id.Bill_list, R.id.Tip_list};
Cursor NewEntry = showData.GetRowByName(selectedName);
startManagingCursor(NewEntry);
lv2.setAdapter(new SimpleCursorAdapter(ctx, R.layout.listlayout, NewEntry, columns, to));
showData.close();
NewEntry.close();
// Back Button Functionality
Button backButton = (Button) findViewById(R.id.Back);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), Tipscreen.class);
startActivityForResult(myIntent, 0);
}
}
);
}
}
Here is my XML Files
listlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/ID_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10px" />
<TextView
android:id="#+id/Name_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10px" />
<TextView
android:id="#+id/Bill_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10px" />
<TextView
android:id="#+id/Tip_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10px"/> </LinearLayout>
-- databaseinfoscreen.xml --
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<ListView android:text="List" android:id="#+id/List1" android:layout_width="wrap_content" android:textSize="18px" android:layout_height="fill_parent">
</ListView>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<ListView android:text="List" android:id="#+id/List2" android:layout_width="wrap_content" android:textSize="18px" android:layout_height="fill_parent">
</ListView>
</LinearLayout>
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<Button android:text="#string/back" android:layout_alignParentBottom="true" android:id="#+id/Back" android:layout_width="wrap_content" android:textSize="18px" android:layout_height="40px"></Button>
</RelativeLayout>
</LinearLayout>
Hopefully this is enough to go off of, if there is any more information needed please let me know. I am getting all the information I need in the cursor it just isn't being displayed. I am open to alternate means of doing this. However, I cannot make this particular class extend ListActivity since it needs to be extending activity.
Also of note. I have been able to display to that listview using the following line of code. Unfortunately this is only displays one column rather than all columns which I want.
lv2.setAdapter(new ArrayAdapter<String>(ctx, android.R.layout.simple_gallery_item, FinalString));
Where FinalString is simply a full column of data from the database that was manipulated into an array.
Thanks for the help.
Well since no one responded, I figured I'd answer this myself.
Here are the steps, I've got this working for a different project so I'll summarize. I can go into more detail if anyone needs it.
XML:
<ListView android:text="List" android:id="#+id/android:list" android:layout_width="wrap_content" android:scrollbars="horizontal" android:textSize="18px" android:layout_height="fill_parent" android:minHeight="120px">
</ListView>
Step 1: Create a Cursor and populate using DB functions (not shown)
String dbCount = showData.getTotalCount();
Cursor GetAllData = showData.GetAllData();
startManagingCursor(GetAllData);
Step 2: Create an ArrayList that comprises a bunch of get values and fill the list with items from the cursor.
int i = GetAllData.getCount();
ArrayList<DB_Get_Values> dbList = new ArrayList<DB_Get_Values>();
while (GetAllData.moveToNext()) {
DB_Get_Values w = new DB_Get_Values(GetAllData.getString(0), GetAllData.getString(1), GetAllData.getString(2));
dbList.add( w );
j++;
}
Step 3: Create an adapter class that will be used to control the display of the listview
DBAdapter T_Adapter = new DBAdapter(
this,
dbList );
setListAdapter( T_Adapter );
GetAllData.close();
DB_Get_Values Class: Full of Getters
public class DB_Get_Values {
public String P_Key = "";
public String Mac_addr = "";
public String SDK_VRS = "";
public DB_Get_Values( String P_Key, String Mac_addr, String SDK_VRS)
{
this.P_Key = P_Key;
this.Mac_addr = Mac_addr;
this.SDK_VRS = SDK_VRS;
}
public String get_Mac_addr() {
return Mac_addr;
}
public String get_P_Key() {
return P_Key;
}
public String get_SDK_VRS() {
return SDK_VRS;
}
}
Class DBAdapter: Get's the values to put into the listview and allows for programatically controlling the display.
class AdapterView extends LinearLayout {
public AdapterView(Context context,
DB_Get_Values list ) {
super( context );
this.setOrientation(HORIZONTAL);
LinearLayout.LayoutParams PkeyParams =
new LinearLayout.LayoutParams(40, LayoutParams.WRAP_CONTENT);
PkeyParams.setMargins(1, 1, 1, 1);
TextView Pkey = new TextView( context );
Pkey.setText( list.get_P_Key() );
Pkey.setTextSize(14f);
Pkey.setTextColor(Color.WHITE);
addView( Pkey, PkeyParams);
LinearLayout.LayoutParams MacAddrParams =
new LinearLayout.LayoutParams(100, LayoutParams.WRAP_CONTENT);
MacAddrParams.setMargins(1, 1, 1, 1);
TextView MacAddr = new TextView( context );
MacAddr.setText( list.get_Mac_addr() );
MacAddr.setTextSize(14f);
MacAddr.setTextColor(Color.WHITE);
addView( MacAddr, MacAddrParams);
LinearLayout.LayoutParams SDK_VRSParams =
new LinearLayout.LayoutParams(20, LayoutParams.WRAP_CONTENT);
SDK_VRSParams.setMargins(1, 1, 1, 1);
TextView SDK_VRS = new TextView( context );
SDK_VRS.setText( list.get_SDK_VRS() );
SDK_VRS.setTextSize(14f);
SDK_VRS.setTextColor(Color.WHITE);
addView( SDK_VRS, SDK_VRSParams);
}
}
public class DBAdapter extends BaseAdapter {
private Context context;
private List<DB_Get_Values> list;
public DBAdapter(Context context, List<DB_Get_Values> list ) {
this.context = context;
this.list = list;
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
}
Step 5: You are now done! Change the parameters in AdapterView class to modify how it looks. Hopefully this helps someone.

Categories

Resources