Android Listview with Listview item - android-listview

I am trying to create a ListView where each item contains a TextItem and a ListView (dynamic length) but for some reason only one item is shown in the inner ListView. Is this something that is not possible or am I doing something wrong?
Here is my layout:
<?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="fill_parent">
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/outerListId"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Inner list item:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profile Name"
android:id="#+id/nameId"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/innerListId"/>
</RelativeLayout>
Code:
public class ListAllActivity extends Activity {
protected class MyListItem {
public String name;
public List<String> items;
public MyListItem(String name) {
this.name = name;
this.items = items();
}
public List<String> items() {
ArrayList<String> strings = new ArrayList<String>();
strings.add("item1");
strings.add("item2");
return strings;
}
}
public class CustomListViewAdapter extends ArrayAdapter<MyListItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId, List<MyListItem> items) {
super(context, resourceId, items);
this.context = context;
}
private class ViewHolder {
TextView nameText;
ListView myList;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
MyListItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.profile_exercises_list_item, null);
holder = new ViewHolder();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.nameText = (TextView) convertView.findViewById(R.id.profileNameListItemId);
holder.myList = (ListView) convertView.findViewById(R.id.innerListId);
List<String> items = rowItem.items();
holder.nameText.setText(rowItem.name);
ArrayAdapter<String> myarrayAdapter = new ArrayAdapter<String>(convertView.getContext(), android.R.layout.simple_list_item_1, items);
holder.myList.setAdapter(myarrayAdapter);
holder.myList.setTextFilterEnabled(true);
return convertView;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
ListView listView = (ListView) findViewById(R.id.outerListId);
ArrayList<MyListItem> allItems = new ArrayList<MyListItem>();
allItems.add(new MyListItem("name1"));
allItems.add(new MyListItem("name2"));
CustomListViewAdapter all = new CustomListViewAdapter(this, android.R.layout.simple_list_item_1, allItems);
listView.setAdapter(all);
listView.setTextFilterEnabled(true);
}
}

Instead of using Nested ListViews, you can use Expandable ListView.
Here are some useful links for playing with expandable ListView.
http://www.dreamincode.net/forums/topic/270612-how-to-get-started-with-expandablelistview/
http://android-adda.blogspot.com/2011/06/custom-expandable-listview.html

Related

Displaying Navigation drawer in all activities problem

I'm making a navigation drawer with different activities and i want to display the same navigation drawer in all activities , i take the same code and put it in all activities but when i click on the activities my app crashes all the time i don't know why
Try below code for displaying Navigation drawer on all activity, hope this example help...!
BaseActivity
public class BaseActivity extends AppCompatActivity {
ArrayList<String> menuList;
protected FrameLayout frameLayout;
protected ListView mDrawerList;
protected static int position;
private static boolean isLaunch = true;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
#SuppressLint("ResourceAsColor")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.navigation_drawer_base_layout);
prepareListItems();
frameLayout = findViewById(R.id.content_frame);
mDrawerLayout = findViewById(R.id.drawer_layout);
mDrawerList = findViewById(R.id.left_drawer);
View header = getLayoutInflater().inflate(R.layout.header, null);
mDrawerList.addHeaderView(header);
mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, menuList));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
openActivity(position);
}
});
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.menu);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.mipmap.ic_launcher_round, /* nav drawer image to replace 'Up' caret */
R.string.open_drawer, /* "open drawer" description for accessibility */
R.string.close_drawer) /* "close drawer" description for accessibility */ {
#Override
public void onDrawerClosed(View drawerView) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
Objects.requireNonNull(getSupportActionBar()).setTitle(getString(R.string.app_name));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
if (isLaunch) {
isLaunch = false;
openActivity(1);
}
}
private void prepareListItems() {
menuList = new ArrayList<>();
menuList.add(" Activity1 ");
menuList.add(" Activity2 ");
menuList.add(" Activity3 ");
menuList.add(" Activity4 ");
}
/**
* #param position Launching activity when any list item is clicked.
*/
protected void openActivity(int position) {
mDrawerList.setItemChecked(position - 1, true);
mDrawerLayout.closeDrawer(mDrawerList);
BaseActivity.position = position; //Setting currently selected position in this field so that it will be available in our child activities.
switch (position) {
case 0:
break;
case 1:
startActivity(new Intent(this, Activity1.class));
break;
case 2:
startActivity(new Intent(this, Activity2.class));
break;
case 3:
startActivity(new Intent(this, Activity3.class));
break;
case 4:
startActivity(new Intent(this, Activity4.class));
break;
default:
break;
}
// Toast.makeText(this, "Selected Item Position::" + position, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
}
Activity1
public class Activity1 extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_main, frameLayout);
mDrawerList.setItemChecked(position, true);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
navigation_drawer_base_layout
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#drawable/simple_brushed_metal"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</androidx.drawerlayout.widget.DrawerLayout>
header
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/shade">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="serif"
android:gravity="center"
android:text="#string/app_name"
android:textColor="#color/textColorPrimary"
android:textSize="18sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/developed_by_nd_software_solution"
android:textColor="#color/textColorPrimary"
android:textSize="12sp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="8dp"
android:background="#color/textColorPrimary" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
drawer_list_item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/activatedBackgroundIndicator"
android:fontFamily="serif"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/textColorPrimary" />
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:fontFamily="serif"
android:gravity="center"
android:text="#string/app_name"
android:textColor="#color/textColorPrimary"
android:textSize="18sp" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here I have provided code for one activity (Activity1), write code for other activities like Activity2, Activity3 etc.

Adding image and childitem in a listview in android

I'm a beginner to android n m tryin to display a listview wer i'll have an image, items n subitems(childitem).. i tried it but m unable to c the image and the subitem of the list.. here's my code :-
activity_main :-
<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"
tools:context=".MainActivity">
<TextView
android:id="#+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
listview_layout:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/hello"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
/>
<TextView
android:id="#+id/cur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
/>
</LinearLayout>
MainActivity :-
public class MainActivity extends Activity {
// Array of strings storing country names
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[]{
R.drawable.india,
R.drawable.pakistan,
R.drawable.srilanka,
R.drawable.china,
R.drawable.bangladesh,
R.drawable.nepal,
R.drawable.afghanistan,
R.drawable.nkorea,
R.drawable.skorea,
R.drawable.japan
};
// Array of strings to store currencies
String[] currency = new String[]{
"Indian Rupee",
"Pakistani Rupee",
"Sri Lankan Rupee",
"Renminbi",
"Bangladeshi Taka",
"Nepalese Rupee",
"Afghani",
"North Korean Won",
"South Korean Won",
"Japanese Yen"
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Country : " + countries[i]);
hm.put("cur","Currency : " + currency[i]);
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.listview,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
// Item Click Listener for the listview
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
LinearLayout linearLayoutParent = (LinearLayout) container;
// Getting the inner Linear Layout
LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);
// Getting the Country TextView
TextView tvCountry = (TextView) linearLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), tvCountry.getText().toString(), Toast.LENGTH_SHORT).show();
}
};
// Setting the item click listener for the listview
listView.setOnItemClickListener(itemClickListener);
}
In the output the listview just displays the country name.. the image and the currency values are not displayed.. wht m i missin ?

android preferencefragment listview arrayadapter getview not called

After researching / reviewing code the past couple days, a solution eludes me. The ArrayAdapter.getView() function is not being called.
ArrayAdapter.getCount() is returning 3.
This listview is similar to the WiFi preference fragment ..
https://android.googlesource.com/platform/packages/apps/Settings.git/+/6829c48c36fceebb46989f8ee25c369fa5f7adeb/src/com/android/settings/wifi/WifiSettings.java
The code samples at GitHub (using title search terms) show that this should be working.
Queries through stackoverflow for "getView not called" have suggested that
the List was not being passed in,
the count was not being returned,
the ArrayAdapter was not attached to the ListView properly using setListAdapter vs setAdapter
the ArrayAdapter and ListView scope need to be class vs method level
the ListView may not be visible, thus android knows it would not be able to draw it on the screen so getView() method is never called to render the objects.
Provided below are the PreferenceFragment and ArrayAdapter Classes, and XML files.
Your Thoughts?
PreferenceFragment Class
public class Settings_WebServers extends PreferenceFragment
{
protected MyAdapter adapter = null;
protected ListView lv = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
addPreferencesFromResource(R.xml.settings_webservers);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView (inflater, container, savedInstanceState);
View v = inflater.inflate (R.layout.webservers, container, false);
List<String> strings = new ArrayList<String> ();
strings.add ("WebServer 1");
strings.add ("WebServer 2");
strings.add ("WebServer 3");
adapter = new MyAdapter (container.getContext(), R.layout.webservers_list, strings);
lv = (ListView) v.findViewById (android.R.id.list);
lv.setAdapter (adapter);
return v;
}
#Override
public void onStart()
{
super.onStart();;
Log.d ("onStart ", "Entered Function" );
Log.d ("ListView ", String.valueOf(lv.isShown()?"shown":"hidden"));
}
// ArrayAdapter embedded class
ArrayAdapter Class
private class MyAdapter extends ArrayAdapter<String>
{
Context context;
List<String> strings = new ArrayList<String>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId, List<String> objects)
{
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.strings = objects;
this.context = context;
}
#Override
public int getCount ()
{ return (strings.size()); }
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
Log.d ("getView position", String.valueOf (position) );
TextView lblServerName = null;
String current = strings.get (position);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate
(R.layout.webservers_list, parent, false);
lblServerName = (TextView) convertView.findViewById (R.id.txtServerName);
if (lblServerName != null)
lblServerName.setText (String.valueOf(current));
return convertView;
}
}
}
Preference Header Segment
<header
android:fragment="ENetArch.Todo.Settings_WebServers"
android:icon="#drawable/icon_server"
android:title="WebServers"
android:summary="A list of servers to synchronize with"/>
xml.settings.webservers.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</PreferenceScreen>
layout.webservers.xml
<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="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
layout.webservers_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="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<TextView
android:id="#+id/txtServerName"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:text="ENetArch"
/>
</LinearLayout>
Log Trace
04-25 15:33:02.840: D/onCreateView(2941): Entered Function
04-25 15:33:02.930: D/MyAdapter(2941): construct entered
04-25 15:33:02.930: D/MyAdapter(2941): construct exited
04-25 15:33:02.950: D/getCount(2941): 3
04-25 15:33:02.950: D/getCount(2941): 3
04-25 15:33:02.950: D/onCreateView(2941): Exiting Function
04-25 15:33:03.070: D/onStart(2941): Entered Function
04-25 15:33:03.070: D/ListView(2941): hidden

How to select the rating bar in List Adapter in android?

Eventhough this question has been asked by users many number of times,I am not able to solve my problem by going through all the posts.I have used list view in android.And to the listview i have added the rating bar,text view and some other child items.I am able to select only the entire list item.I want to select the individual list items.I will paste the code which i have tried.
public class ReviewAdapter extends ArrayAdapter<String>{
private final Context context;
private final String[] values;
public ReviewAdapter(Context context, String[] values) {
super(context,R.layout.activity_reviewlist,values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater layoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView =layoutInflater.inflate(R.layout.activity_reviewlist, parent,false);
TextView tv1 = (TextView) rowView.findViewById(R.id.textView1);
TextView tv2 = (TextView) rowView.findViewById(R.id.textView2);
TextView tv3 = (TextView) rowView.findViewById(R.id.textView3);
TextView tv4 = (TextView) rowView.findViewById(R.id.textView4);
TextView tv5 = (TextView) rowView.findViewById(R.id.textView5);
RatingBar ratingbar = (RatingBar) rowView.findViewById(R.id.ratingBar1);
ratingbar.setIsIndicator(true);
ImageView im1 = (ImageView) rowView.findViewById(R.id.imageView1);
tv1.setText(values[position]);
String s = values[position];
if(s.equals("Speech for Presentation")){
tv2.setText("07 th May 2011 22:30");
tv3.setText("05:30");
tv4.setText("Attempts");
tv5.setText("5");
}
else if(s.equals("Slide Show Presentation")){
tv2.setText("08 th May 2011 21:15");
tv3.setText("04:12");
tv4.setText("Attempts");
tv5.setText("7");
}
else if(s.equals("Seminar Presentation")){
tv2.setText("09 th May 2011 10:15");
tv3.setText("08:26");
tv4.setText("Attempts");
tv5.setText("9");
}
else if(s.equals("Training Speech")){
tv2.setText("10 th May 2011 9:16");
tv3.setText("09:26");
tv4.setText("Attempts");
tv5.setText("3");
}
else{
tv2.setText("12 th May 2011 10:10");
tv3.setText("19:26");
tv4.setText("Attempts");
tv5.setText("7");
}
return rowView;
}
}
And now i am going to paste my list activity here
public class ReviewActivity extends ListActivity {
static final String[] reviews = new String[] {"Speech for Presentation","Slide Show Presentation","Seminar Presentation","Training Speech","Promoting the product"};
protected void onListItemClick(ListView l, View v, int position, long id) {
//get selected items
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ReviewAdapter(this, reviews));
}
}
Lastly iam pasting the xml which i have tried.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RatingBar
android:id="#+id/ratingBar1"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
android:layout_marginTop="33dp"
android:isIndicator="true"
/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/ratingBar1"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="26dp"
android:text="TextView" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/textView2"
android:src="#drawable/timer" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/imageView1"
android:text="TextView" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_marginLeft="18dp"
android:layout_toRightOf="#+id/textView3"
android:text="TextView" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView4"
android:layout_alignRight="#+id/ratingBar1"
android:text="TextView" />
</RelativeLayout>

Progress bar isn't working

I am new to android ,I want make an app which needs a progress bar, but the code which I wrote seems to crash each time I run it .As till now I am unable to find the bug.I am using a vertical progress bar.
thanx in advance.
package com.example.progtask;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends Activity implements OnClickListener, Runnable {
private ProgressBar pb;
private Button show;
private Button hide;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
show = (Button) findViewById(R.id.button1);
hide = (Button) findViewById(R.id.hide);
// pb.setVisibility(ProgressBar.GONE);
show.setOnClickListener(this);
hide.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(show)) {
pb.setVisibility(ProgressBar.VISIBLE);
pb.setProgress(0);
pb.setMax(12);
new Thread(this).start();
} else {
pb.setVisibility(ProgressBar.GONE);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
int n = 0;
while (n < 10) {
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
pb.setProgress(n);
}
}
Below is the Xml file
<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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text="picelate"
tools:context=".MainActivity" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="82dp"
android:layout_toLeftOf="#+id/textView1"
android:text="show" />
<Button
android:id="#+id/hide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button1"
android:layout_alignBottom="#+id/button1"
android:layout_toRightOf="#+id/textView1"
android:text="hide" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignParentLeft="true" />
</RelativeLayout>
Try this
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button1:
pb.setVisibility(ProgressBar.VISIBLE);
pb.setProgress(0);
pb.setMax(12);
new Thread(this).start();
break;
case R.id.hide:
// do the needful.
break;
}
}
This is how it worked:
public class MainActivity extends Activity implements OnClickListener, Runnable {
private ProgressBar pb;
private Button show;
private Button hide;
int n;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb = (ProgressBar) findViewById(R.id.progressBar1);
show = (Button) findViewById(R.id.button1);
hide = (Button) findViewById(R.id.button2);
// pb.setVisibility(ProgressBar.GONE);
show.setOnClickListener(this);
hide.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.button1:
pb.setVisibility(ProgressBar.VISIBLE);
pb.setProgress(0);
pb.setMax(100);
n = 0;
new Thread(this).start();
break;
case R.id.button2:
// do the needful.
pb.setVisibility(ProgressBar.GONE);
break;
}
}
#Override
public void run() {
// TODO Auto-generated method stub
int n = 0;
while (n < 100) {
n++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}pb.setProgress(n*10);
}
pb.setProgress(n*10);
}
}
the xml file is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hide" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progressDrawable="#drawable/progbar"
android:layout_gravity="bottom"
/>
</LinearLayout>