Change TextView with Intent (String) - android

I have a listview class.listview opening and a user can click any listview item. I wanna set the text on a xml. I have strings like st1-st2-st3. If I clicked any listview item, how can I get it to open the xml and set Textview1 for st1/#String ?
my listview working like this ;
public class strateji extends Activity {
private static final String LOG_TAG = "Alert Dialog Activity";
private ListView lv1;
private TextView status;
private String lv_arr[]={"listview1-list2-list3-list4-list5-list6-etc..."};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ana);
// Look up the AdView as a resource and load a request.
Log.i(LOG_TAG, "Alert Dialog Activity Started");
lv1=(ListView)findViewById(R.id.listView1);
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position == 0)
{
setContentView(R.layout.texts); //--->opening texts.xml and setText
status.setText(String);--------->>> like this i want send a string for TextView
}
if(position == 1)
{
Intent myIntent = new Intent(strateji.this, mat2.class);
startActivityForResult(myIntent, 0);
}
}
}

Ok this is getting a bit confusing so let me just do this.
If you have a layout like this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:packpurchase="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/text_view_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="17sp"
android:padding="15dp" />
<View
android:id="#+id/divider_one"
android:layout_width="match_parent"
android:layout_height="1dp" />
<ListView
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:divider="#drawable/list_divider_inset"
android:dividerHeight="1dp" >
</ListView>
</LinearLayout>
In your activity, create the variables in order to have a reference to your views and adapter:
private ListView lv;
private ArrayAdapter<String> mAdapter;
private TextView tv;
And then in onCreate() once you are done calling super.onCreate() and setContentView(), set your adapter to your ListView while getting your references
lv = (ListView) findViewById(android.R.id.list);
mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr);
lv1.setAdapter(mAdapter);
tv = (TextView) findViewById(R.id.your_textview_id);
lv1.setOnItemClickListener(new OnitemClickListener(){
#Override
public void onItemClicked(...){
// GET YOUR STRING
String mString = mAdapter.getItem(position);
// APPLY YOUR STRING TO YOUR TEXT_VIEW
tv.setText(mString);
}
};
Again this is poorly explained and I am not sure if it is correct to what you need. It is just to get you started (or at least to help us understand better what you need).
Note that you don't have to keep a reference to your adapter as you can just call
lv1.getAdapter().getItem(position);
I just keep a reference to it and often see a reference to the adapter kept. Same with TextView tv. You don't have to keep a reference, but you can and once you have that reference you can do null checks to avoid doing to many findViewById() calls which can get heavy.

If I understand you correctly, you want a new activity to open and a textview in that activity to display text thats dependent on what list view item they clicked?
you would add an intent extra into your intent that you are using to launch the new activity and put the string you want displayed into it, and then in the new activity get that extra and then set the text view to it.
Intent i = new Intent(activity1, activity2);
i.putExtra(stringkey, stringvalue);
then in your oncreate of the activity you call
String str = getIntent.getStringExtra(stringkey);
then just set the textview to that string

Related

Create list view with custom set of data in android?

I am trying to create ListView with custom data set as follows:
String superType = "random1";
String superTypea = "random12";
String superType12 = "random2";
String superType_amount = "child1";
String childtype_calulated = "2323";
String superType_amount = "child2";
String childtype_calulated = "23223";
String superType_amount = "child2";
String childtype_calulated = "amount3";
Now I want to create ListView with this set of data how to do that?
Here is the list structure...
row1=superType |superType_amount |childtype_calulated
row2=superTypea |superType_amount |childtype_calulated
row3=superType12|superType_amount |childtype_calulated
Is there any solution of this?
It is absolutely possible to do this. First, I would recommend putting your data into a collection. It would be preferable to put them into an object and then a collection of those objects. From there you can add a ListView to your main layout, define a custom layout for your list items, and populate your ListView using an ArrayAdapter.
Here is a really good example of how you can do this well. It includes examples of loading data from an external source, which you don't need.
However, if you're getting into development now I would suggest you look into RecyclerView as well. RecyclerView is new and included in the AppCompat v7 library for use on pre-Lollipop Android. A RecyclerView will be a little more complicated to implement for a simple list but is significantly more scalable and efficient. I believe it is Google's intention to replace ListView with RecyclerView entirely in the future.
Here is a pretty simple introduction to making a list with RecyclerView.
EDIT
Using an ArrayAdapter with a ListView. First you need to create a model to store your data, some kind of class that you can put into a collection, for example:
public class Item {
public String title;
public String sub1;
public String sub2;
public void Item(String t, String s1, String s2) {
title = t;
sub1 = s1;
sub2 = s2;
}
}
Then you need to define the layout for the item in your list:
<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/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/sub1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/sub2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Then in you need to make your custom ArrayAdapter by extending the ArrayAdapter class:
public class ItemAdapter extends ArrayAdapter<Item> {
public ItemAdapter(Context context, ArrayList<Item> items) {
super(context, 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Item item = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_layout, parent, false);
}
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView sub1 = (TextView) convertView.findViewById(R.id.sub1);
TextView sub2 = (TextView) convertView.findViewById(R.id.sub2);
title.setText(item.title);
sub1.setText(item.sub1);
sub2.setText(item.sub2);
return convertView;
}
}
Then all you need to do is create an instance of the adapter in your main class and attach your collection to it:
ArrayList<Item> data = new ArrayList<Item>();
ItemAdapter adapter = new ItemAdapter(this, data);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
This should populate your ListView with all the items that you need in your list. I haven't run any of this code so there might be one or two small bugs for you to fix.

List view is not getting displayed

Hi I have created a simple application for displaying contents from database to list view, but my list view is not displaying any data I am a beginner and I need some assistance.
Giving my list view class below
public class Show extends Activity {
//SQLiteDatabase db;
//Datahelper dh;
Context context=this;
Dataclass dc;
private ListView mainListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
mainListView=(ListView)findViewById(R.id.list);
//getDetails();
dc=new Dataclass(this);
Bundle bundle=getIntent().getExtras();
String message=bundle.getString("MSG");
List<String> friendlist=dc.getDetails(message);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_activated_1,friendlist);
mainListView.setAdapter(adapter);
}
public void onDestroy() {
super.onDestroy();
dc.close();
}
}
I have passed data from one activity to this activity using bundle and I have got the data , but no data is retrieved from the database..
giving m y getdetails function from dataclass below
public List<String> getDetails(String message) {
List<String> Friendlist = new ArrayList<String>();
String selectQuery="SELECT * FROM Mytables WHERE Name='" + message + "' ";
db = dh.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
while(cursor.moveToNext()) {
Friendlist.add(cursor.getString(1));
}
return Friendlist;
}
giving my xml layout for list activity below
<?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/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
try set listview's background color to red, see it is NO-CONTENT or DIDN'T DISPLAY.
From your layout I can see that you don't have an ListView element with id "list" mainListView=(ListView)findViewById(R.id.list);. Since all the operations you are running assume the existence of this element, probably this is the reason why nothing appears on the screen.
I also suggest that instead of inheriting from Activity you should inherit from ListActivity and use existing methods to deal with ListView like getListView(), setListAdapter(adapter) and keep your ListView with the default id android:id="#android:id/list".

ListViewItems opens same Activity but with different content

I have a ListView that gets TutorialTitels from the string file like so
public class tutorialActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial);
registerClickCallBack();
ListView listView = (ListView) findViewById(R.id.tutorialList);
String tutorialTitle1 = getResources().getString(R.string.tutorial1_title);
String tutorialTitle2 = getResources().getString(R.string.tutorial2_title);
String tutorialTitle3 = getResources().getString(R.string.tutorial3_title);
String tutorialTitle4 = getResources().getString(R.string.tutorial4_title);
String tutorialTitle5 = getResources().getString(R.string.tutorial5_title);
String tutorialTitle6 = getResources().getString(R.string.tutorial6_title);
String tutorialTitle7 = getResources().getString(R.string.tutorial7_title);
String tutorialTitle8 = getResources().getString(R.string.tutorial8_title);
String tutorialTitle9 = getResources().getString(R.string.tutorial9_title);
String tutorialTitle10 = getResources().getString(R.string.tutorial10_title);
String tutorialTitle11 = getResources().getString(R.string.tutorial11_title);
String tutorialTitle12 = getResources().getString(R.string.tutorial12_title);
String tutorialTitle13 = getResources().getString(R.string.tutorial13_title);
String tutorialTitle14 = getResources().getString(R.string.tutorial14_title);
String[] values = new String[] { tutorialTitle1, tutorialTitle2, tutorialTitle3, tutorialTitle4, tutorialTitle5, tutorialTitle6, tutorialTitle7, tutorialTitle8, tutorialTitle9, tutorialTitle10, tutorialTitle11, tutorialTitle12, tutorialTitle13, tutorialTitle14};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
private void registerClickCallBack() {
ListView list = (ListView) findViewById(R.id.tutorialList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,int position, long id) {
}
});
}
}
When I click on a listViewItem then I'd like to open up an Activity that'll show the following things:
The clicked TutorialTitel
Tutorial content (This will also come from a string file, like so
String tutorialContent1 = getResources().getString(R.string.tutorial1_content);)
Tutorial example ((This will also come from a string file, like so
String tutorialExample1 = getResources().getString(R.string.tutorial1_example);))
I already have an XML file like so
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#FFFFFF"
android:orientation="vertical"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" >
<TextView
android:id="#+id/tutorialTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Title"
android:textSize="25sp" />
<LinearLayout
android:id="#+id/split"
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_marginBottom="15dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_marginTop="5dp"
android:background="#38b34a"
android:orientation="horizontal" />
<TextView
android:id="#+id/tutorialContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text=""/>
<TextView
android:id="#+id/tutorialExample"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text=""/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
The question: How do I pass the data to my activity corresponding to my clicked ListviewItem? should I do something like
if(position == 0){
//Send data through extra bundle
}
else if(position == 1){
//send data through extra bundle
}
But there should be a better way I think, but I don't know how exactly, because what if I'll getting 100 tutorials how should I manage a list long like that?
Can someone point me in the correct direction and what is the best approach to do this?
You can add a listener to ListView using setOnItemClickListener(); this listener callback will give three parameter as onItemClick (AdapterView<?> parent, View view, int position, long id) in which position will give the position of the list item clicked.
so using this position you can use as values[position] and same for tutorialContent and tutorialExample and pass it in intent and start Activity with this intent having the selected item data
This is a Quick solution for your problem. But i will not recommend because the way you have implemented is not in the object oriented standard.
I recommend you to create a model class for Tutorial with having member variable title, content, and example.
Class Tutorial{
private String title;
private String content;
private string example;
}
and pass this object in the intent.
First keep your strings in an array file (array.xml). Then read them to an String array;
String [] myresources=resources.obtainTypedArray(R.array.somelist);
for(int i=0;i<NumberOfTutorials;i++){
if(position==i){
//send myresources[i];
}
}
You can use enum. For example you can define Tutorials enum like this:
public enum Tutorials
{
TUTORIAL_1(R.string.tutorial1_title, R.string.tutorial1_content, R.string.tutorial1_example),
TUTORIAL_2(R.string.tutorial2_title, R.string.tutorial2_content, R.string.tutorial2_example),
TUTORIAL_3(R.string.tutorial3_title, R.string.tutorial3_content, R.string.tutorial3_example);
private int mTitleResourceId;
private int mContentResourceId;
private int mExampleResourceId;
private Tutorials(int titleResourceId, int contentResourceId, int exampleResourceId)
{
mTitleResourceId = titleResourceId;
mContentResourceId = contentResourceId;
mExampleResourceId = exampleResourceId;
}
public int getTitleResourceId()
{
return mTitleResourceId;
}
public int getContentResourceId()
{
return mContentResourceId;
}
public int getExampleResourceId()
{
return mExampleResourceId;
}
}
In this enum you can define 100 tutorials if you wish.
And then in your activity you can use it like this in generic way:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial);
ListView listView = (ListView) findViewById(R.id.tutorialList);
List<String> titlesList = new ArrayList<String>();
for (Tutorials tutorial: Tutorials.values())
{
titlesList.add(getResources().getString(tutorial.getTitleResourceId()));
}
String[] values = titlesList.toArray(new String[titlesList.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
And finally on click item on the list you can easily retrieve the Tutorial enum by its string title and then you will have the tutorial content and and tutorial example for free.
Once you set this code, you will add tutorials only to Tutorials enum and that's it.
Hope it helps. Of course, using sqlite is also an option.

Updating crossed-out items on loading ListView

I am fairly new to Android programming and trying to set items in a listview upon loading the information from internal storage.
I have two global arrays that I am using: first one is a String array that has the names of the items in the list, and the second is a boolean array that keeps track of which items are crossed out. I am using a TextView in the listview.
main_activity.xml:
<ListView
android:id="#+id/listViewMyList"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
rowlayout.xml:
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:layout_marginBottom="3dp"
android:text="#+id/label" />
I have created an onClickListener() which successfully updates the state of each list item:
public class MainActivity extends Activity
{
// Initialize the list (global list values)
String[] values = new String[0]; // array of items for the list
boolean[] checkedVals = new boolean[0]; // keep track of which items are crossed-off
String localFileName = "myListData.csv";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// read the data from file if present
readListFromFile();
// find the ListView
ListView lst = (ListView) findViewById(R.id.listViewMyList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.rowlayout, R.id.label, values);
lst.setAdapter(adapter);
// define what happens on click
lst.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// read crossed status and set text flags for strikethrough
if (checkedVals[position])
{
TextView text1 = (TextView)view.findViewById(R.id.label);
text1.setPaintFlags(text1.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
text1.setTextColor(0xff000000);
checkedVals[position] = false;
}
else
{
TextView text1 = (TextView)view.findViewById(R.id.label);
text1.setPaintFlags(text1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
text1.setTextColor(0xff888888);
checkedVals[position] = true;
}
// save the data in a file
saveListToFile();
}
});
}
So this code works fine for crossing out and un-crossing out the items. I don't know how can I cross-out some of the items (determined by the checkedVals boolean array) without clicking or any activity when I load the list.
Thanks in advance.
You need to create a custom Adapter by extending ArrayAdapter and overriding getView().
The getView() method loads every row's layout, this is where you should check if the row is in your checkedVals array and draw with the appropriate flags. This Google Talk by an Android lead programmer, Romain Guy, provide a wealth of information about best practices on how to do this.

ListView inside LinearLayout no longer reacts to OnclickListener

I am designing a simple app from tutorials that I have seen, and I am attempting to simply display two text views in each row of a listview, a name and a price. This worked and I could select the row and it would activate an intent. However I then changed my xml code so that the listview would be placed in a linearLayout in order for me to have a header at the top of the screen. Now when I click on any of the rows they are highlighted but nothing else happens. I have already tried to making the textviews set to clickable = false in the xml but still no luck. I am hoping I am just missing something simple in the onCreate method. `public class ViewMenuListing extends ListActivity {
public static final String ROW_ID = "row_id"; // Intent extra key
private ListView contactListView; // the ListActivity's ListView
private CursorAdapter contactAdapter; // adapter for ListView
private String tableName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
contactListView = getListView(); // get the built-in ListView
contactListView.setOnItemClickListener(viewContactListener);
setContentView(R.layout.viewmenu);
//Get table name of menu clicked.
Bundle extras = getIntent().getExtras();
tableName = extras.getString("table");
// map each contact's name to a TextView in the ListView layout
String[] from = new String[] { "name", "price" };
int[] to = new int[] { R.id.itemTextView, R.id.priceTextView };
//int[] to = new int[] { R.id.itemTextView};
contactAdapter = new SimpleCursorAdapter(
ViewMenuListing.this, R.layout.menu_list_item, null, from, to);
setListAdapter(contactAdapter); // set contactView's adapter
}`
The only thing I changed in this code was that I used the setContentView(R.layout.viewmenu) now when I didnt before and the list would just be the content view.
Here is my viewMenu file:
`
<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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello" />
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>`
and my menu_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemTextView"
android:padding="8dp"
android:clickable = "false"
android:textSize="20sp" android:textColor="#android:color/white"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/priceTextView"
android:clickable = "false"
android:textColor="#android:color/white"/>
</LinearLayout>
Thank you for your help!
Looks like you are explicitly setting an onItemClickListener for your ListView. This really isn't necessary since you are extending ListActivity and ListActivity has a method you can override called onListItemClick(). I would override the onListItemClick() method instead of explicitly setting an onItemClickListener. http://developer.android.com/reference/android/app/ListActivity.html#onListItemClick(android.widget.ListView, android.view.View, int, long)
Please correct following things
contactListView = getListView(); and setListAdapter(contactAdapter);
The above syntax can be only used if your class is extending ListActivity .In your case you are extending Activity,So above Approach will not work.
Your menu_list_item.xml looks perfectly fine to me.
in viewmenu.xml file make following correction while specifying id for listview.
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Please see to this corrected code.
public class SampleActivity extends ListActivity
{
public static final String ROW_ID = "row_id"; // Intent extra key
private ListView contactListView; // the ListActivity's ListView
private CursorAdapter contactAdapter; // adapter for ListView
private String tableName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
contactListView = (ListView) findViewById(R.id.list); // get the
// built-in
// ListView
contactListView.setOnItemClickListener(this);
setContentView(R.layout.viewmenu);
Bundle extras = getIntent().getExtras();
tableName = extras.getString("table");
// map each contact's name to a TextView in the ListView layout
String[] from = new String[]
{ "name", "price" };
int[] to = new int[]
{ R.id.itemTextView, R.id.priceTextView };
contactAdapter = new SimpleCursorAdapter(SampleActivity.this,
R.layout.menu_list_item, null, from, to);
contactListView.setAdapter(contactAdapter);
}
#Override
public void onListItemClick(AdapterView<?> adapterView, View view,
int position, long arg3)
{
}
}
Now in onListItemClick method you can write whatever logic you want.
Hope this help.

Categories

Resources