Search Results

Search found 911 results on 37 pages for 'textview'.

Page 12/37 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • adding a UIScrollView as a superview of 2 UITextview made no view can be scrolled

    - by Risma
    hi i have 2 textview in a viewcontroller. the 1st textview is not editable, but the 2nd is editable. i want to make both of them scroll in the same position and size when the keyboard is appear. I think i have to use UIScrollView as base of both of textview. And then i add the UIScrollView in xib (bot of textview are made in xib too). and this is the picture if this hierarchy : in the viewDidLoad method, i add this code : - (void)viewDidLoad { [super viewDidLoad]; [scrollTextView addSubview:lineNumberTextView]; [scrollTextView addSubview:_codeTextView]; [lineNumberTextView bringSubviewToFront:scrollTextView]; [_codeTextView bringSubviewToFront:scrollTextView]; } but after that i can't scroll anything. What i have to do? thx for the advices

    Read the article

  • Explain to me the following VS 2010 Extension Sample code..

    - by ealshabaan
    Coders, I am building a VS 2010 extension and I am experimenting around some of the samples that came with the VS 2010 SDK. One of the sample projects is called TextAdornment. In that project there is a weirdo class that looks like the following: [Export(typeof(IWpfTextViewCreationListener))] [ContentType("text")] [TextViewRole(PredefinedTextViewRoles.Document)] internal sealed class TextAdornment1Factory : IWpfTextViewCreationListener While I was experimenting with this project, I tried to debug the project to see the flow of the program and I noticed that this class gets hit when I first start the debugging. Now my question is the following: what makes this class being the first class to get called when VS starts? In other words, why this class gets active and it runs as of some code instantiate an object of this class type? Here is the only two files in the sample project: TextAdornment1Factory.cs using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace TextAdornment1 { #region Adornment Factory /// /// Establishes an to place the adornment on and exports the /// that instantiates the adornment on the event of a 's creation /// [Export(typeof(IWpfTextViewCreationListener))] [ContentType("text")] [TextViewRole(PredefinedTextViewRoles.Document)] internal sealed class TextAdornment1Factory : IWpfTextViewCreationListener { /// /// Defines the adornment layer for the adornment. This layer is ordered /// after the selection layer in the Z-order /// [Export(typeof(AdornmentLayerDefinition))] [Name("TextAdornment1")] [Order(After = PredefinedAdornmentLayers.Selection, Before = PredefinedAdornmentLayers.Text)] [TextViewRole(PredefinedTextViewRoles.Document)] public AdornmentLayerDefinition editorAdornmentLayer = null; /// <summary> /// Instantiates a TextAdornment1 manager when a textView is created. /// </summary> /// <param name="textView">The <see cref="IWpfTextView"/> upon which the adornment should be placed</param> public void TextViewCreated(IWpfTextView textView) { new TextAdornment1(textView); } } #endregion //Adornment Factory } TextAdornment1.cs using System.Windows; using System.Windows.Controls; using System.Windows.Media; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Formatting; namespace TextAdornment1 { /// ///TextAdornment1 places red boxes behind all the "A"s in the editor window /// public class TextAdornment1 { IAdornmentLayer _layer; IWpfTextView _view; Brush _brush; Pen _pen; ITextView textView; public TextAdornment1(IWpfTextView view) { _view = view; _layer = view.GetAdornmentLayer("TextAdornment1"); textView = view; //Listen to any event that changes the layout (text changes, scrolling, etc) _view.LayoutChanged += OnLayoutChanged; _view.Closed += new System.EventHandler(_view_Closed); //selectedText(); //Create the pen and brush to color the box behind the a's Brush brush = new SolidColorBrush(Color.FromArgb(0x20, 0x00, 0x00, 0xff)); brush.Freeze(); Brush penBrush = new SolidColorBrush(Colors.Red); penBrush.Freeze(); Pen pen = new Pen(penBrush, 0.5); pen.Freeze(); _brush = brush; _pen = pen; } void _view_Closed(object sender, System.EventArgs e) { MessageBox.Show(textView.Selection.IsEmpty.ToString()); } /// <summary> /// On layout change add the adornment to any reformatted lines /// </summary> private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e) { foreach (ITextViewLine line in e.NewOrReformattedLines) { this.CreateVisuals(line); } } private void selectedText() { } /// <summary> /// Within the given line add the scarlet box behind the a /// </summary> private void CreateVisuals(ITextViewLine line) { //grab a reference to the lines in the current TextView IWpfTextViewLineCollection textViewLines = _view.TextViewLines; int start = line.Start; int end = line.End; //Loop through each character, and place a box around any a for (int i = start; (i < end); ++i) { if (_view.TextSnapshot[i] == 'a') { SnapshotSpan span = new SnapshotSpan(_view.TextSnapshot, Span.FromBounds(i, i + 1)); Geometry g = textViewLines.GetMarkerGeometry(span); if (g != null) { GeometryDrawing drawing = new GeometryDrawing(_brush, _pen, g); drawing.Freeze(); DrawingImage drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); Image image = new Image(); image.Source = drawingImage; //Align the image with the top of the bounds of the text geometry Canvas.SetLeft(image, g.Bounds.Left); Canvas.SetTop(image, g.Bounds.Top); _layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); } } } } } }

    Read the article

  • Model View Control Issue: Null Pointer Initialization Question

    - by David Dimalanta
    Good morning again. This is David. Please, I need an urgent help regarding control model view where I making a code that uniquely separating into groups: An Activity Java Class to Display the Interface A View and Function Java Class for Drawing Cards and Display it on the Activity Class The problem is that the result returns a Null Pointer Exception. I have initialize for the ID for Text View and Image View. Under this class "draw_deck.java". Please help me. Here's my code for draw_deck.java: package com.bodapps.inbetween.model; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bodapps.inbetween.R; public class draw_deck extends View { public TextView count_label; public ImageView draw_card; private int count; public draw_deck(Context context) { super(context); // TODO Auto-generated constructor stub //I have initialized two widgets for ID. I still don't get it why I got forced closed by Null Pointer Exception thing. draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); } public void draw(int s, int c, String strSuit, String strValue, Pile pile, Context context) { //super(context); //Just printing the card drawn from pile int suit, value = 1; draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); Card card; if(!pile.isEmpty()) //Setting it to IF statement displays the card one by one. { card = pile.drawFromPile(); //Need to check first if card is null. if (card != null) { //draws an extra if (card != null) { //Get suit of card to print out. suit = card.getSuit(); switch (suit) { case CardInfo.DIAMOND: strSuit = "DIAMOND"; s=0; break; case CardInfo.HEART: strSuit = "HEART"; s=1; break; case CardInfo.SPADE: strSuit = "SPADE"; s=2; break; case CardInfo.CLUB: strSuit = "CLUB"; s=3; break; } //Get value of card to print out. value = card.getValue(); switch (value) { case CardInfo.ACE: strValue = "ACE"; c=0; break; case CardInfo.TWO: c=1; break; case CardInfo.THREE: strValue = "THREE"; c=2; break; case CardInfo.FOUR: strValue = "FOUR"; c=3; break; case CardInfo.FIVE: strValue = "FIVE"; c=4; break; case CardInfo.SIX: strValue = "SIX"; c=4; break; case CardInfo.SEVEN: strValue = "SEVEN"; c=4; break; case CardInfo.EIGHT: strValue = "EIGHT"; c=4; break; case CardInfo.NINE: strValue = "NINE"; c=4; break; case CardInfo.TEN: strValue = "TEN"; c=4; break; case CardInfo.JACK: strValue = "JACK"; c=4; break; case CardInfo.QUEEN: strValue = "QUEEN"; c=4; break; case CardInfo.KING: strValue = "KING"; c=4; break; } } } }// //Below two lines of code, this is where issued the Null Pointer Exception. draw_card.setImageResource(deck[s][c]); count_label.setText(new StringBuilder(strValue).append(" of ").append(strSuit).append(String.valueOf(" " + count++)).toString()); } //Choice of Suits in a Deck public Integer[][] deck = { //Array Group 1 is [0][0] (No. of Cards: 4 - DIAMOND) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 2 is [1][0] (No. of Cards: 4 - HEART) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 3 is [2][0] (No. of Cards: 4 - SPADE) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 4 is [3][0] (No. of Cards: 4 - CLUB) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, }; } And this one of the activity class, Player_Mode_2.java: package com.bodapps.inbetween; import java.util.Random; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bodapps.inbetween.model.Card; import com.bodapps.inbetween.model.Pile; import com.bodapps.inbetween.model.draw_deck; /* * * Public class for Two-Player mode. * */ public class Player_Mode_2 extends Activity { //Image Views private ImageView draw_card; private ImageView player_1; private ImageView player_2; private ImageView icon; //Buttons private Button set_deck; //Edit Texts private EditText enter_no_of_decks; //text Views private TextView count_label; //Integer Data Types private int no_of_cards, count; private int card_multiplier; //Contexts final Context context = this; //Pile Model public Pile pile; //Card Model public Card card; //create View @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.play_2_player_mode); //-----[ Search for Views ]----- //Initialize for Image View draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); player_1 = (ImageView) findViewById(R.id.IV_Player_1_Card); player_2 = (ImageView) findViewById(R.id.IV_Player_2_Card); //Initialize for Text view or Label count_label = (TextView) findViewById(R.id.Text_View_Count_Card); //-----[ Adding Values ]----- //Integer Values count = 0; no_of_cards = 0; //-----[ Adding Dialog ]----- //Initializing Dialog final Dialog deck_dialog = new Dialog(context); deck_dialog.setContentView(R.layout.dialog); deck_dialog.setTitle("Deck Dialog"); //-----[ Initializing Views for Dialog's Contents ]----- //Initialize for Edit Text enter_no_of_decks = (EditText) deck_dialog.findViewById(R.id.Edit_Text_Set_Number_of_Decks); //Initialize for Button set_deck = (Button) deck_dialog.findViewById(R.id.Button_Deck); //-----[ Setting onClickListener() ]----- //Set Event Listener for Image view draw_card.setOnClickListener(new Draw_Card_Model()); //Set Event Listener for Setting the Deck set_deck.setOnClickListener(new OnClickListener() { public void onClick(View v) { if(card_multiplier <= 8) { //Use "Integer.parseInt()" method to instantly convert from String to int value. card_multiplier = Integer.parseInt(enter_no_of_decks.getText().toString()); //Shuffling cards... pile = new Pile(card_multiplier); //Multiply no. of decks //Dismiss or close the dialog. deck_dialog.dismiss(); } else { Toast.makeText(getApplicationContext(), "Please choose a number from 1 to 8.", Toast.LENGTH_SHORT).show(); } } }); //Show dialog. deck_dialog.show(); } //Shuffling the Array public void Shuffle_Cards(Integer[][] Shuffle_Deck) { Random random = new Random(); for(int i = Shuffle_Deck[no_of_cards].length - 1; i >=0; i--) { int Index = random.nextInt(i + 1); //Simple Swapping Integer swap = Shuffle_Deck[card_multiplier-1][Index]; Shuffle_Deck[card_multiplier-1][Index] = Shuffle_Deck[card_multiplier-1][i]; Shuffle_Deck[card_multiplier-1][i] = swap; } } //Private Class for Random Card Draw private class Draw_Card_Model implements OnClickListener { public void onClick(View v) { //Just printing the card drawn from pile int suit = 0, value = 0; String strSuit = "", strValue = ""; draw_deck draw = new draw_deck(context); //This line is where issued the Null Pointer Exception. if (count == card_multiplier*52) { // A message shows up when all cards are draw out. Toast.makeText(getApplicationContext(), "All cards have been used up.", Toast.LENGTH_SHORT).show(); draw_card.setEnabled(false); } else { draw.draw(suit, value, strSuit, strValue, pile, context); count_label.setText(count); //This is where I got force closed error, although "int count" have initialized the number. This was supposed to accept in the setText() method. count++; } } } } Take note that the issues on Null Pointer Exception is the Image View and the Edit Text. I got to test it. Thanks. If you have any info about my question, let me know it frankly.

    Read the article

  • Model View Control Issue: Null Pointer Initialization Question [closed]

    - by David Dimalanta
    Good morning again. This is David. Please, I need an urgent help regarding control model view where I making a code that uniquely separating into groups: An Activity Java Class to Display the Interface A View and Function Java Class for Drawing Cards and Display it on the Activity Class The problem is that the result returns a Null Pointer Exception. I have initialize for the ID for Text View and Image View. Under this class "draw_deck.java". Please help me. Here's my code for draw_deck.java: package com.bodapps.inbetween.model; import android.content.Context; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bodapps.inbetween.R; public class draw_deck extends View { public TextView count_label; public ImageView draw_card; private int count; public draw_deck(Context context) { super(context); // TODO Auto-generated constructor stub //I have initialized two widgets for ID. I still don't get it why I got forced closed by Null Pointer Exception thing. draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); } public void draw(int s, int c, String strSuit, String strValue, Pile pile, Context context) { //super(context); //Just printing the card drawn from pile int suit, value = 1; draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); count_label = (TextView) findViewById(R.id.Text_View_Count_Card); Card card; if(!pile.isEmpty()) //Setting it to IF statement displays the card one by one. { card = pile.drawFromPile(); //Need to check first if card is null. if (card != null) { //draws an extra if (card != null) { //Get suit of card to print out. suit = card.getSuit(); switch (suit) { case CardInfo.DIAMOND: strSuit = "DIAMOND"; s=0; break; case CardInfo.HEART: strSuit = "HEART"; s=1; break; case CardInfo.SPADE: strSuit = "SPADE"; s=2; break; case CardInfo.CLUB: strSuit = "CLUB"; s=3; break; } //Get value of card to print out. value = card.getValue(); switch (value) { case CardInfo.ACE: strValue = "ACE"; c=0; break; case CardInfo.TWO: c=1; break; case CardInfo.THREE: strValue = "THREE"; c=2; break; case CardInfo.FOUR: strValue = "FOUR"; c=3; break; case CardInfo.FIVE: strValue = "FIVE"; c=4; break; case CardInfo.SIX: strValue = "SIX"; c=4; break; case CardInfo.SEVEN: strValue = "SEVEN"; c=4; break; case CardInfo.EIGHT: strValue = "EIGHT"; c=4; break; case CardInfo.NINE: strValue = "NINE"; c=4; break; case CardInfo.TEN: strValue = "TEN"; c=4; break; case CardInfo.JACK: strValue = "JACK"; c=4; break; case CardInfo.QUEEN: strValue = "QUEEN"; c=4; break; case CardInfo.KING: strValue = "KING"; c=4; break; } } } }// //Below two lines of code, this is where issued the Null Pointer Exception. draw_card.setImageResource(deck[s][c]); count_label.setText(new StringBuilder(strValue).append(" of ").append(strSuit).append(String.valueOf(" " + count++)).toString()); } //Choice of Suits in a Deck public Integer[][] deck = { //Array Group 1 is [0][0] (No. of Cards: 4 - DIAMOND) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 2 is [1][0] (No. of Cards: 4 - HEART) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 3 is [2][0] (No. of Cards: 4 - SPADE) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, //Array Group 4 is [3][0] (No. of Cards: 4 - CLUB) { R.drawable.card_dummy_1, R.drawable.card_dummy_2, R.drawable.card_dummy_4, R.drawable.card_dummy_5, R.drawable.card_dummy_3 }, }; } And this one of the activity class, Player_Mode_2.java: package com.bodapps.inbetween; import java.util.Random; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bodapps.inbetween.model.Card; import com.bodapps.inbetween.model.Pile; import com.bodapps.inbetween.model.draw_deck; /* * * Public class for Two-Player mode. * */ public class Player_Mode_2 extends Activity { //Image Views private ImageView draw_card; private ImageView player_1; private ImageView player_2; private ImageView icon; //Buttons private Button set_deck; //Edit Texts private EditText enter_no_of_decks; //text Views private TextView count_label; //Integer Data Types private int no_of_cards, count; private int card_multiplier; //Contexts final Context context = this; //Pile Model public Pile pile; //Card Model public Card card; //create View @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.play_2_player_mode); //-----[ Search for Views ]----- //Initialize for Image View draw_card = (ImageView) findViewById(R.id.IV_Draw_Card); player_1 = (ImageView) findViewById(R.id.IV_Player_1_Card); player_2 = (ImageView) findViewById(R.id.IV_Player_2_Card); //Initialize for Text view or Label count_label = (TextView) findViewById(R.id.Text_View_Count_Card); //-----[ Adding Values ]----- //Integer Values count = 0; no_of_cards = 0; //-----[ Adding Dialog ]----- //Initializing Dialog final Dialog deck_dialog = new Dialog(context); deck_dialog.setContentView(R.layout.dialog); deck_dialog.setTitle("Deck Dialog"); //-----[ Initializing Views for Dialog's Contents ]----- //Initialize for Edit Text enter_no_of_decks = (EditText) deck_dialog.findViewById(R.id.Edit_Text_Set_Number_of_Decks); //Initialize for Button set_deck = (Button) deck_dialog.findViewById(R.id.Button_Deck); //-----[ Setting onClickListener() ]----- //Set Event Listener for Image view draw_card.setOnClickListener(new Draw_Card_Model()); //Set Event Listener for Setting the Deck set_deck.setOnClickListener(new OnClickListener() { public void onClick(View v) { if(card_multiplier <= 8) { //Use "Integer.parseInt()" method to instantly convert from String to int value. card_multiplier = Integer.parseInt(enter_no_of_decks.getText().toString()); //Shuffling cards... pile = new Pile(card_multiplier); //Multiply no. of decks //Dismiss or close the dialog. deck_dialog.dismiss(); } else { Toast.makeText(getApplicationContext(), "Please choose a number from 1 to 8.", Toast.LENGTH_SHORT).show(); } } }); //Show dialog. deck_dialog.show(); } //Shuffling the Array public void Shuffle_Cards(Integer[][] Shuffle_Deck) { Random random = new Random(); for(int i = Shuffle_Deck[no_of_cards].length - 1; i >=0; i--) { int Index = random.nextInt(i + 1); //Simple Swapping Integer swap = Shuffle_Deck[card_multiplier-1][Index]; Shuffle_Deck[card_multiplier-1][Index] = Shuffle_Deck[card_multiplier-1][i]; Shuffle_Deck[card_multiplier-1][i] = swap; } } //Private Class for Random Card Draw private class Draw_Card_Model implements OnClickListener { public void onClick(View v) { //Just printing the card drawn from pile int suit = 0, value = 0; String strSuit = "", strValue = ""; draw_deck draw = new draw_deck(context); //This line is where issued the Null Pointer Exception. if (count == card_multiplier*52) { // A message shows up when all cards are draw out. Toast.makeText(getApplicationContext(), "All cards have been used up.", Toast.LENGTH_SHORT).show(); draw_card.setEnabled(false); } else { draw.draw(suit, value, strSuit, strValue, pile, context); count_label.setText(count); //This is where I got force closed error, although "int count" have initialized the number. This was supposed to accept in the setText() method. count++; } } } } Take note that the issues on Null Pointer Exception is the Image View and the Edit Text. I got to test it. Thanks. If you have any info about my question, let me know it frankly.

    Read the article

  • android app working on simulator but not on phone

    - by raqz
    i have this app that i developed and it works great on the simulator with no errors what so ever. but the moment i try to run the same on the phone for testing, the app crashes stating filenotfoundexception. it says the file /res/drawable/divider_horizontal.9.png is missing. but actually speaking, i have never referenced that file through my code. i believe its a system/os file that is unavailable. i have a custom list view, i guess its the divider there... could somebody please suggest what is wrong here. i believe this is a similar issue discussed here..but i am unable to make any sense out of it http://code.google.com/p/transdroid/issues/detail?id=14 the listview.xml layout file <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:gravity="left|center" android:layout_width="wrap_content" android:paddingBottom="5px" android:paddingTop="5px" android:paddingLeft="5px" > <ImageView android:id="@+id/linkImage" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="6dip" android:src="@drawable/icon" /> <LinearLayout android:orientation="vertical" android:layout_width="0dip" android:layout_weight="1" android:layout_height="fill_parent"> <TextView android:id="@+id/firstLineView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textColor="#FFFF00" android:text="first line title"></TextView> <TextView android:id="@+id/secondLineView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="second line title" android:layout_marginLeft="10px" android:gravity="center" android:textColor="#0099CC"></TextView> </LinearLayout> </LinearLayout> the main xml file that calls the listview.xml <?xml version="1.0" encoding="UTF-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout 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="40px"> <Button android:id="@+id/todayButton" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Today" android:textSize="12sp" android:gravity="center" android:layout_weight="1" /> <Button android:id="@+id/tomorrowButton" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Tomorrow" android:textSize="12sp" android:layout_weight="1" /> <Button android:id="@+id/WeekButton" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Future" android:textSize="12sp" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:id="@+id/listLayout" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/ListView01" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <TextView android:id="@id/android:empty" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="No Results" /> </LinearLayout> </LinearLayout> </FrameLayout> and the code for the same is private class EfficientAdapter extends BaseAdapter{ private LayoutInflater mInflater; private String eventTitleArray[]; private String eventDateArray[]; private String eventImageLinkArray[]; public EfficientAdapter(Context context,String[] eventTitleArray,String[] eventDateArray, String[] eventImageLinkArray){ mInflater = LayoutInflater.from(context); this.eventDateArray=eventDateArray; this.eventTitleArray=eventTitleArray; this.eventImageLinkArray =eventImageLinkArray; } public int getCount(){ //return XmlParser.todayEvents.size()-1; return this.eventDateArray.length; } public Object getItem(int position){ return position; } public long getItemId(int position){ return position; } public View getView(int position, View convertView, ViewGroup parent){ ViewHolder holder; if(convertView == null){ convertView = mInflater.inflate(R.layout.listview,null); holder = new ViewHolder(); holder.firstLine = (TextView) convertView.findViewById(R.id.firstLineView); holder.secondLine = (TextView) convertView.findViewById(R.id.secondLineView); holder.imageView = (ImageView) convertView.findViewById(R.id.linkImage); //holder.checkbox = (CheckBox) convertView.findViewById(R.id.star); holder.firstLine.setFocusable(false); holder.secondLine.setFocusable(false); holder.imageView.setFocusable(false); //holder.checkbox.setFocusable(false); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } Log.i(tag, "Creating the list"); holder.firstLine.setText(this.eventTitleArray[position]); holder.secondLine.setText(this.eventDateArray[position]); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://eventur.sis.pitt.edu/images/heinz7.jpg").getContent()); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (Exception e1) { // TODO Auto-generated catch block bitmap = BitmapFactory.decodeFile("assets/heinz7.jpg");//decodeFile(getResources().getAssets().open("icon.png")); e1.printStackTrace(); } try { try{ bitmap = BitmapFactory.decodeStream((InputStream)new URL(this.eventImageLinkArray[position]).getContent());} catch(Exception e){ bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://eventur.sis.pitt.edu/images/heinz7.jpg").getContent()); } int width = 0; int height =0; int newWidth = 50; int newHeight = 40; try{ width = bitmap.getWidth(); height = bitmap.getHeight(); } catch(Exception e){ width = 50; height = 40; } float scaleWidth = ((float)newWidth)/width; float scaleHeight = ((float)newHeight)/height; Matrix mat = new Matrix(); mat.postScale(scaleWidth, scaleHeight); try{ Bitmap newBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,mat,true); BitmapDrawable bmd = new BitmapDrawable(newBitmap); holder.imageView.setImageDrawable(bmd); holder.imageView.setScaleType(ScaleType.CENTER); } catch(Exception e){ } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return convertView; } class ViewHolder{ TextView firstLine; TextView secondLine; ImageView imageView; //CheckBox checkbox; } The stack trace 12-12 22:55:25.022: ERROR/AndroidRuntime(11069): Uncaught handler: thread main exiting due to uncaught exception 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): android.view.InflateException: Binary XML file line #6: Error inflating class java.lang.reflect.Constructor 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.LayoutInflater.createView(LayoutInflater.java:512) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:562) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.LayoutInflater.rInflate(LayoutInflater.java:617) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.LayoutInflater.inflate(LayoutInflater.java:407) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at com.eventur.MainActivity$EfficientAdapter.getView(MainActivity.java:566) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.AbsListView.obtainView(AbsListView.java:1274) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.ListView.makeAndAddView(ListView.java:1661) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.ListView.fillDown(ListView.java:610) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.ListView.fillFromTop(ListView.java:673) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.ListView.layoutChildren(ListView.java:1519) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.AbsListView.onLayout(AbsListView.java:1113) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.View.layout(View.java:6156) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.LinearLayout.onLayout(LinearLayout.java:918) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.View.layout(View.java:6156) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.LinearLayout.onLayout(LinearLayout.java:918) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.View.layout(View.java:6156) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.View.layout(View.java:6156) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.View.layout(View.java:6156) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.LinearLayout.onLayout(LinearLayout.java:918) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.View.layout(View.java:6156) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.View.layout(View.java:6156) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.ViewRoot.performTraversals(ViewRoot.java:950) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.ViewRoot.handleMessage(ViewRoot.java:1529) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.os.Handler.dispatchMessage(Handler.java:99) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.os.Looper.loop(Looper.java:123) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.app.ActivityThread.main(ActivityThread.java:3977) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at java.lang.reflect.Method.invokeNative(Native Method) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at java.lang.reflect.Method.invoke(Method.java:521) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at dalvik.system.NativeStart.main(Native Method) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): Caused by: java.lang.reflect.InvocationTargetException 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.ImageView.<init>(ImageView.java:128) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at java.lang.reflect.Constructor.constructNative(Native Method) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at java.lang.reflect.Constructor.newInstance(Constructor.java:446) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.view.LayoutInflater.createView(LayoutInflater.java:499) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): ... 42 more 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): Caused by: android.content.res.Resources$NotFoundException: File res/drawable/divider_horizontal_dark.9.png from drawable resource ID #0x7f020001 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.content.res.Resources.loadDrawable(Resources.java:1643) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.content.res.TypedArray.getDrawable(TypedArray.java:548) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.widget.ImageView.<init>(ImageView.java:138) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): ... 46 more 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): Caused by: java.io.FileNotFoundException: res/drawable/divider_horizontal_dark.9.png 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.content.res.AssetManager.openNonAssetNative(Native Method) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.content.res.AssetManager.openNonAsset(AssetManager.java:417) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): at android.content.res.Resources.loadDrawable(Resources.java:1636) 12-12 22:55:25.212: ERROR/AndroidRuntime(11069): ... 48 more

    Read the article

  • How to maintain the state of button cutom listview in android

    - by Akshay
    I have custom ListView with three TextView three Button and three Chronometer. And the situation is I am loading the ListView properly.But while loading ListView I am disabling some button in the ListView by checking one parameter. Up to this point ListView is showing it's row properly. But when I am scrolling the ListView at that time previously enabled Button are getting disabled.What I am doing wrong I am not getting can one please point out my mistake Or any suggestion. Here is my Adapter class. public class OrderSmartKitchenAdapter extends BaseAdapter { private int flagDeliveryComplete = 0; private int flagPreparationComplete = 0; private int flagPreparationStarted = 0; private List<OrderitemdetailsBO> list = new ArrayList<OrderitemdetailsBO(); private int orderStatus; public OrderSmartKitchenAdapter() { // TODO Auto-generated constructor stub } public void setOrderList(List<OrderitemdetailsBO> orderList) { this.list = orderList; } @Override public int getCount() { // TODO Auto-generated method stub Log.i("OrderItemList Size :-", Integer.toString(list.size())); return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(final int position, View convertView,ViewGroup parent) { // TODO Auto-generated method stub final ViewHolder viewHolder ; if (convertView == null) { layoutInflater = LayoutInflater.from(myContext); convertView = layoutInflater.inflate(R.layout.table_row_view,null); viewHolder = new ViewHolder(); viewHolder.txtTableNumber = (TextView) convertView.findViewById(R.id.txtTableNumber); viewHolder.txtMenuItem = (TextView) convertView.findViewById(R.id.txtMenuItem); viewHolder.txtQuantity = (TextView) convertView.findViewById(R.id.txtQuantity); viewHolder.txtOrderAcceptanceTime = (TextView) convertView.findViewById(R.id.txtOrderAcceptanceTime); viewHolder.txtElapsedTimeOfOrderAcceptance = (Chronometer) convertView.findViewById(R.id.txtElapsedTimeOfOrderAcceptance); viewHolder.btnPreparationStart = (Button) convertView.findViewById(R.id.btnPreparationStart); viewHolder.btnPreparationStart.setTag(position); viewHolder.txtElapsedTimeForPreparation = (Chronometer) convertView.findViewById(R.id.txtElapsedTimeForPrepatration); viewHolder.btnPreparationComplete = (Button) convertView.findViewById(R.id.btnPreparationCompleted); viewHolder.btnPreparationComplete.setTag(position); viewHolder.txtElapsedTimeForDeliveryComplete = (Chronometer) convertView.findViewById(R.id.txtElapsedTimeForCompleation); viewHolder.btnDeliveryComplete = (Button) convertView.findViewById(R.id.btnOrderComplete); viewHolder.btnDeliveryComplete.setTag(position); convertView.setTag(viewHolder); } else{ viewHolder = (ViewHolder)convertView.getTag(); viewHolder.btnDeliveryComplete.setTag(position); viewHolder.btnPreparationComplete.setTag(position); viewHolder.btnPreparationStart.setTag(position); } if (list.get(position) != null) { OrderitemdetailsBO orderitemdetailsBO = new OrderitemdetailsBO(); orderitemdetailsBO = list.get(position); viewHolder.txtTableNumber.setText(orderitemdetailsBO.getOrderitemid().toString()); viewHolder.txtMenuItem.setText(orderitemdetailsBO.getMenuitemname().toString()); viewHolder.txtQuantity.setText(orderitemdetailsBO.getQuantity().toString()); Log.i("Table Number :-", Long.toString(orderitemdetailsBO.getOrderitemid())); Log.i("Menu Name :-", orderitemdetailsBO.getMenuitemname().toString()); Log.i("Quantity", orderitemdetailsBO.getQuantity().toString()); Date acceptTime = new Date(); acceptTime = orderitemdetailsBO.getOrderdatetime(); viewHolder.txtOrderAcceptanceTime.setText(DateUtil.getDateAsString(acceptTime,"HH:mm")); Log.i("Order Accept Time :-", acceptTime.getMinutes() + ":"+ acceptTime.getSeconds()); orderStatus = orderitemdetailsBO.getOrderstatus(); Date preparationStartTime = new Date(); preparationStartTime = orderitemdetailsBO.getPreparationstarttime(); if(preparationStartTime != null) { Log.i("OrderSmartKitchenActivity", "2 Order Acceptance Time :-" + "Menu Item id "+ orderitemdetailsBO.getOrderitemid() + " Preparation Start time " + orderitemdetailsBO.getPreparationstarttime() ); viewHolder.txtElapsedTimeOfOrderAcceptance.stop(); Log.i("Preparation Start Time :-",preparationStartTime.getMinutes() + ":" + preparationStartTime.getSeconds()); viewHolder.txtElapsedTimeOfOrderAcceptance.setText(DateUtil.getDateAsString(preparationStartTime,"MM:ss")); viewHolder.txtElapsedTimeOfOrderAcceptance.stop(); viewHolder.btnPreparationStart.setEnabled(false); viewHolder.btnPreparationStart.setClickable(false); viewHolder.btnPreparationStart.setBackgroundColor(Color.LTGRAY); } else { Long n = acceptTime.getTime(); Log.i("OrderSmartKitchenActivity", "Order Acceptance Time :-" + "Menu Item id "+ orderitemdetailsBO.getOrderitemid() + " Acceptance time" + Long.toString(n) + " Preparation Start time " + orderitemdetailsBO.getPreparationstarttime() ); // Calculate Time difference viewHolder.txtElapsedTimeOfOrderAcceptance.setBase(SystemClock.elapsedRealtime() - System.currentTimeMillis() + n); viewHolder.txtElapsedTimeOfOrderAcceptance.getBase(); viewHolder.txtElapsedTimeOfOrderAcceptance.start(); viewHolder.txtElapsedTimeOfOrderAcceptance.setFormat("%s"); } viewHolder.btnPreparationStart.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { // TODO Auto-generated method stub if (flagPreparationStarted == 0) { flagPreparationStarted++; v.startAnimation(playAnimation()); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub v.clearAnimation(); Date currentTime = new Date(); // Set Preparation Start Time. viewHolder.txtElapsedTimeOfOrderAcceptance.stop(); Date setTime = new Date(currentTime.getTime() * 1000); OrderitemdetailsBO orderitemdetailsBO = list.get(position); orderitemdetailsBO.setPreparationstarttime(setTime); String orderDetails = "2"; String getPosition = Integer.toString(position); viewHolder.btnPreparationStart.setBackgroundColor(Color.LTGRAY); new sendOrderStatusToServer().execute(orderDetails,getPosition); } }, 5000); } else { handler.removeCallbacksAndMessages(null); v.clearAnimation(); flagPreparationStarted = 0; Log.i("Handler Removed. :-", "Here"); } } }); String preparationTime = orderitemdetailsBO.getOrderpreparationtime(); if(preparationTime != null && orderStatus == order_preparationComplete) { viewHolder.txtElapsedTimeForPreparation.setText(preparationTime); viewHolder.txtElapsedTimeForPreparation.stop(); viewHolder.btnPreparationComplete.getTag(position); viewHolder.btnPreparationComplete.setEnabled(false); viewHolder.btnPreparationComplete.setClickable(false); viewHolder.btnPreparationComplete.setBackgroundColor(Color.LTGRAY); } else if( orderStatus == order_preparationStart || orderStatus == orderReceived || orderStatus == order_delivered){ Long n = acceptTime.getTime(); Log.i("Preparation Start Time :-", Long.toString(n)); viewHolder.txtElapsedTimeForPreparation.setBase(SystemClock.elapsedRealtime() - System.currentTimeMillis() + n); viewHolder.txtElapsedTimeForPreparation.getBase(); viewHolder.txtElapsedTimeForPreparation.start(); viewHolder.txtElapsedTimeForPreparation.setFormat("%s"); } viewHolder.btnPreparationComplete.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { // TODO Auto-generated method if (flagPreparationComplete == 0) { flagPreparationComplete++; v.startAnimation(playAnimation()); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub v.clearAnimation(); OrderitemdetailsBO orderitemdetailsBO = list.get(position); Date date = orderitemdetailsBO.getPreparationstarttime(); if(date != null) { viewHolder.txtElapsedTimeForPreparation.stop(); Date currentTime = new Date(); Calendar calendar = Calendar.getInstance(); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); orderitemdetailsBO.setOrderpreparationtime(calendar.get(Calendar.MINUTE) +":" +calendar.get(Calendar.SECOND)); String orderDetails = "3"; String getPosition = Integer.toString(position); viewHolder.btnPreparationComplete.setBackgroundColor(Color.LTGRAY); new sendOrderStatusToServer().execute(orderDetails,getPosition); } else { Toast.makeText(myContext, "Please Enter Preparation Start Time.", Toast.LENGTH_LONG).show(); } } }, 5000); } else { handler.removeCallbacksAndMessages(null); v.clearAnimation(); flagPreparationComplete = 0; } } }); String deleveredTime = orderitemdetailsBO.getOrderdeliverytime(); if(deleveredTime != null && orderStatus == order_delivered) { Date delevered = new Date(Long.parseLong(deleveredTime)); viewHolder.txtElapsedTimeForPreparation.setText(DateUtil.getDateAsString(delevered,"MM:ss")); Log.i("Preparation Start Time :-", delevered.getMinutes()+":"+delevered.getSeconds()); viewHolder.txtElapsedTimeForPreparation.stop(); viewHolder.btnDeliveryComplete.getTag(position); viewHolder.btnDeliveryComplete.setEnabled(false); viewHolder.btnDeliveryComplete.setClickable(false); viewHolder.btnDeliveryComplete.setBackgroundColor(Color.LTGRAY); } else if(orderStatus == 3 || orderStatus == 2 || orderStatus == 1) { Long n = acceptTime.getTime(); Log.i("Preparation Start Time :-", Long.toString(n)); viewHolder.txtElapsedTimeForDeliveryComplete.setTag(list.get(position)); viewHolder.txtElapsedTimeForDeliveryComplete.setBase(SystemClock.elapsedRealtime() - System.currentTimeMillis() + n); viewHolder.txtElapsedTimeForDeliveryComplete.getBase(); viewHolder.txtElapsedTimeForDeliveryComplete.start(); viewHolder.txtElapsedTimeForDeliveryComplete.setFormat("%s"); } viewHolder.btnDeliveryComplete.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { // TODO Auto-generated method stub if (flagDeliveryComplete == 0) { flagDeliveryComplete++; v.startAnimation(playAnimation()); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub v.clearAnimation(); OrderitemdetailsBO orderitemdetailsBO = list.get(position); Date date = orderitemdetailsBO.getPreparationstarttime(); String preparationComplete = orderitemdetailsBO.getOrderpreparationtime(); if(date != null && preparationComplete != null ) { Date currentTime = new Date(); Calendar calendar = Calendar.getInstance(); viewHolder.txtElapsedTimeForDeliveryComplete.stop(); orderitemdetailsBO.setOrderdeliverytime(calendar.get(Calendar.MINUTE) +":"+calendar.get(Calendar.SECOND)); String orderDetails = Integer.toString(order_delivered); String getPosition = Integer.toString(position); viewHolder.btnDeliveryComplete.setBackgroundColor(Color.LTGRAY); new sendOrderStatusToServer().execute(orderDetails,getPosition); } else { Toast.makeText(myContext, "Please Enter Preparation Start Time & Preparation Complete Time.", Toast.LENGTH_LONG).show(); } } }, 5000); } else { handler.removeCallbacksAndMessages(null); v.clearAnimation(); flagDeliveryComplete = 0; } } }); } return convertView; } } private static class ViewHolder { protected TextView txtTableNumber; protected TextView txtMenuItem; protected TextView txtQuantity; protected TextView txtOrderAcceptanceTime; protected Chronometer txtElapsedTimeOfOrderAcceptance; protected Button btnPreparationStart; protected Chronometer txtElapsedTimeForPreparation; protected Button btnPreparationComplete; protected Chronometer txtElapsedTimeForDeliveryComplete; protected Button btnDeliveryComplete; }

    Read the article

  • Error with my Android Application httpGet

    - by Coombes
    Basically I'm getting a strange issue with my Android application, it's supposed to grab a JSON Array and print out some values, the class looks like this: ShowComedianActivity.class package com.example.connecttest; public class ShowComedianActivity extends Activity{ TextView name; TextView add; TextView email; TextView tel; String id; // Progress Dialog private ProgressDialog pDialog; //JSON Parser class JSONParser jsonParser = new JSONParser(); // Single Comedian url private static final String url_comedian_details = "http://86.9.71.17/connect/get_comedian_details.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_COMEDIAN = "comedian"; private static final String TAG_ID = "id"; private static final String TAG_NAME = "name"; private static final String TAG_ADDRESS = "address"; private static final String TAG_EMAIL = "email"; private static final String TAG_TEL = "tel"; public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.show_comedian); // Getting Comedian Details from intent Intent i = getIntent(); // Getting id from intent id = i.getStringExtra(TAG_ID); new GetComedianDetails().execute(); } class GetComedianDetails extends AsyncTask<String, String, String>{ protected void onPreExecute(){ super.onPreExecute(); pDialog = new ProgressDialog(ShowComedianActivity.this); pDialog.setMessage("Fetching Comedian details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... params) { runOnUiThread(new Runnable(){ public void run(){ int success; try{ //Building parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("id",id)); // Getting comedian details via HTTP request // Uses a GET request JSONObject json = jsonParser.makeHttpRequest(url_comedian_details, "GET", params); // Check Log for json response Log.d("Single Comedian details", json.toString()); //JSON Success tag success = json.getInt(TAG_SUCCESS); if(success == 1){ // Succesfully received product details JSONArray comedianObj = json.getJSONArray(TAG_COMEDIAN); //JSON Array // get first comedian object from JSON Array JSONObject comedian = comedianObj.getJSONObject(0); // comedian with id found name = (TextView) findViewById(R.id.name); add = (TextView) findViewById(R.id.add); email = (TextView) findViewById(R.id.email); tel = (TextView) findViewById(R.id.tel); // Set text to details name.setText(comedian.getString(TAG_NAME)); add.setText(comedian.getString(TAG_ADDRESS)); email.setText(comedian.getString(TAG_EMAIL)); tel.setText(comedian.getString(TAG_TEL)); } } catch (JSONException e){ e.printStackTrace(); } } }); return null; } } } And my JSON Parser class looks like: package com.example.connecttest; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET method public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } Now when I run a debug it's querying the correct address with ?id=1 on the end of the URL, and when I navigate to that url I get the following JSON Array: {"success":1,"comedian":[{"id":"1","name":"Michael Coombes","address":"5 Trevethenick Road","email":"[email protected]","tel":"xxxxxxxxxxxx"}]} However my app just crashes, the log-cat report looks like this: 03-22 02:05:02.140: E/Trace(3776): error opening trace file: No such file or directory (2) 03-22 02:05:04.590: E/AndroidRuntime(3776): FATAL EXCEPTION: main 03-22 02:05:04.590: E/AndroidRuntime(3776): android.os.NetworkOnMainThreadException 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 03-22 02:05:04.590: E/AndroidRuntime(3776): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 03-22 02:05:04.590: E/AndroidRuntime(3776): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 03-22 02:05:04.590: E/AndroidRuntime(3776): at libcore.io.IoBridge.connect(IoBridge.java:112) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.net.Socket.connect(Socket.java:842) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 03-22 02:05:04.590: E/AndroidRuntime(3776): at com.example.connecttest.JSONParser.makeHttpRequest(JSONParser.java:62) 03-22 02:05:04.590: E/AndroidRuntime(3776): at com.example.connecttest.ShowComedianActivity$GetComedianDetails$1.run(ShowComedianActivity.java:89) 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.Handler.handleCallback(Handler.java:615) 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.Handler.dispatchMessage(Handler.java:92) 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.Looper.loop(Looper.java:137) 03-22 02:05:04.590: E/AndroidRuntime(3776): at android.app.ActivityThread.main(ActivityThread.java:4745) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.lang.reflect.Method.invokeNative(Native Method) 03-22 02:05:04.590: E/AndroidRuntime(3776): at java.lang.reflect.Method.invoke(Method.java:511) 03-22 02:05:04.590: E/AndroidRuntime(3776): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 03-22 02:05:04.590: E/AndroidRuntime(3776): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-22 02:05:04.590: E/AndroidRuntime(3776): at dalvik.system.NativeStart.main(Native Method) From this I'm guessing the error is in the jsonParser.makeHttpRequest however I can't for the life of me figure out what's going wrong and was hoping someone brighter than I could illuminate me.

    Read the article

  • How to sort & Group in Android?

    - by crickpatel0024
    I have ArrayList and I want to sort and group all data by header in Android. How it is possible in Android? please help me.below me from owner And set header Me And Joe Manager From owner And set Header in listview. How to do that in Android? My code in below:: public class Request extends Activity { private String assosiatetoken; private ArrayList<All_Request_data_dto> list = new ArrayList<All_Request_data_dto>(); ListView lv; Button back; private Spinner spndata; String[] reqspinner = { "Request Date", "Last Update", "Type", "Owner", "State" }; ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.request); assosiatetoken = MyApplication.getToken(); new doinbackground(this).execute(); back = (Button) findViewById(R.id.button1); spndata = (Spinner) findViewById(R.id.list_all_quize_req); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, reqspinner); spndata.setAdapter(adapter); lv = (ListView) findViewById(R.id.listrequestdata); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> a, View v, int position, long id) { Intent edit = new Intent(Request.this, Request_webview.class); // edit.putExtra("Cat_url", url_link); startActivity(edit); } }); spndata.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { switch (position) { case 0: list = DBAdpter.requestUserData(assosiatetoken); Collections.sort(list, byDate1); // Collections.reverse(list); for (int i = 0; i < list.size(); i++) { if (list.get(i).submitDate != null) { lv.setAdapter(new MyListAdapter( getApplicationContext(), list)); } } break; case 1: list = DBAdpter.requestUserData(assosiatetoken); Collections.sort(list, byDate); for (int i = 0; i < list.size(); i++) { if (list.get(i).lastModifiedDate != null) { lv.setAdapter(new MyListAdapter( getApplicationContext(), list)); } } break; case 2: list = DBAdpter.requestUserData(assosiatetoken); Collections.sort(list, byDate3); // Collections.reverse(list); for (int i = 0; i < list.size(); i++) { if (list.get(i).state != null) { lv.setAdapter(new MyListAdapter( getApplicationContext(), list)); } } break; case 3: list = DBAdpter.requestUserData(assosiatetoken); for (int i = 0; i < list.size(); i++) { lv.setAdapter(new MyListAdapter( getApplicationContext(), list)); } break; default: break; } } public void onNothingSelected(AdapterView<?> arg0) { } }); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) { java.util.Date d1 = null; java.util.Date d2 = null; try { d1 = sdf.parse(ord1.lastModifiedDate); d2 = sdf.parse(ord2.lastModifiedDate); } catch (java.text.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (d1.getTime() > d2.getTime() ? -1 : 1); // descending // return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending } }; static final Comparator<All_Request_data_dto> byDate1 = new Comparator<All_Request_data_dto>() { SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) { java.util.Date d1 = null; java.util.Date d2 = null; try { d1 = sdf.parse(ord1.submitDate); d2 = sdf.parse(ord2.submitDate); } catch (java.text.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (d1.getTime() > d2.getTime() ? -1 : 1); // descending // return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending } }; static final Comparator<All_Request_data_dto> byDate3 = new Comparator<All_Request_data_dto>() { public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) { String d1 = null; String d2 = null; d1 = ord1.state; d2 = ord2.state; return d1.compareToIgnoreCase(d2); } }; class doinbackground extends AsyncTask<Void, Void, Void> { ProgressDialog pd; private Context ctx; public doinbackground(Context c) { ctx = c; } @Override protected void onPreExecute() { super.onPreExecute(); pd = new ProgressDialog(ctx); pd.setMessage("Loading..."); pd.show(); } @Override protected Void doInBackground(Void... Params) { return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); pd.cancel(); } } public class MyListAdapter extends BaseAdapter { private ArrayList<All_Request_data_dto> list; public MyListAdapter(Context mContext, ArrayList<All_Request_data_dto> list) { this.list = list; } public int getCount() { return list.size(); } public All_Request_data_dto getItem(int position) { return list.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { // if (convertView == null) { LayoutInflater inflator = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); convertView = inflator.inflate(R.layout.custom_request_data, null); TextView req_id = (TextView) convertView.findViewById(R.id.req_txt); TextView date = (TextView) convertView.findViewById(R.id.date_txt); TextView owner = (TextView) convertView .findViewById(R.id.owner_txt); TextView state = (TextView) convertView .findViewById(R.id.state_txt); req_id.setText(list.get(position).requestId + " - " + list.get(position).title); date.setText(list.get(position).lastModifiedDate + " - " + list.get(position).submitDate); owner.setText(list.get(position).owner); state.setText(list.get(position).state); // } return convertView; } } }

    Read the article

  • trying to override getView in a SimpleCursorAdapter gives NullPointerException

    - by Dimitry Hristov
    Would very much appreciate any help or hint on were to go next. I'm trying to change the content of a row in ListView programmatically. In one row there are 3 TextView and a ProgressBar. I want to animate the ProgressBar if the 'result' column of the current row is zero. After reading some tutorials and docs, I came to the conclusion that LayoutInflater has to be used and getView() - overriden. Maybe I am wrong on this. If I return row = inflater.inflate(R.layout.row, null); from the function, it gives NullPointerException. Here is the code: private final class mySimpleCursorAdapter extends SimpleCursorAdapter { private Cursor localCursor; private Context localContext; public mySimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.localCursor = c; this.localContext = context; } /** * 1. ListView asks adapter "give me a view" (getView) for each item of the list * 2. A new View is returned and displayed */ public View getView(int position, View convertView, ViewGroup parent) { View row = super.getView(position, convertView, parent); LayoutInflater inflater = (LayoutInflater)localContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); String result = localCursor.getString(2); int resInt = Integer.parseInt(result); Log.d(TAG, "row " + row); // if 'result' column form the TABLE is 0, do something useful: if(resInt == 0) { ProgressBar progress = (ProgressBar) row.findViewById(R.id.update_progress); progress.setIndeterminate(true); TextView edit1 = (TextView)row.findViewById(R.id.row_id); TextView edit2 = (TextView)row.findViewById(R.id.request); TextView edit3 = (TextView)row.findViewById(R.id.result); edit1.setText("1"); edit2.setText("2"); edit3.setText("3"); row = inflater.inflate(R.layout.row, null); } return row; } here is the Stack Trace: 03-08 03:15:29.639: ERROR/AndroidRuntime(619): java.lang.NullPointerException 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.SimpleCursorAdapter.bindView(SimpleCursorAdapter.java:149) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.CursorAdapter.getView(CursorAdapter.java:186) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at com.dhristov.test1.test1$mySimpleCursorAdapter.getView(test1.java:105) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.AbsListView.obtainView(AbsListView.java:1256) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.ListView.makeAndAddView(ListView.java:1668) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.ListView.fillDown(ListView.java:637) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.ListView.fillSpecific(ListView.java:1224) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.ListView.layoutChildren(ListView.java:1499) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.AbsListView.onLayout(AbsListView.java:1113) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.view.View.layout(View.java:6830) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.LinearLayout.onLayout(LinearLayout.java:918) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.view.View.layout(View.java:6830) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.LinearLayout.onLayout(LinearLayout.java:918) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.view.View.layout(View.java:6830) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.view.View.layout(View.java:6830) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:998) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.LinearLayout.onLayout(LinearLayout.java:918) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.view.View.layout(View.java:6830) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.view.View.layout(View.java:6830) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.view.ViewRoot.performTraversals(ViewRoot.java:996) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.view.ViewRoot.handleMessage(ViewRoot.java:1633) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.os.Handler.dispatchMessage(Handler.java:99) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.os.Looper.loop(Looper.java:123) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at android.app.ActivityThread.main(ActivityThread.java:4363) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at java.lang.reflect.Method.invokeNative(Native Method) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at java.lang.reflect.Method.invoke(Method.java:521) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 03-08 03:15:29.639: ERROR/AndroidRuntime(619): at dalvik.system.NativeStart.main(Native Method)

    Read the article

  • From AutoComplete textbox to database search and display?

    - by svebee
    Hello everyone, I have a small problem so I would be grateful if anyone could help me in any way. Thank you ;) I have this little "application", and I want when someone type in a AutoComplete textbox for example "New" it automatically displays "New York" as a option and that (AutoComplete function) works fine. But I want when user type in full location (or AutoComplete do it for him) - that text (location) input is forwarded to a database search which then searches through database and "collects" all rows with user-typed location. For example if user typed in "New York", database search would find all rows with "New York" in it. When it finds one/more row(s) it would display them below. In images... I have this when user is typing... http://www.imagesforme.com/show.php/1093305_SNAG0000.jpg I have this when user choose a AutoComplete location (h)ttp://www.imagesforme.com/show.php/1093306_SNAG0001.jpg (remove () on the beggining) But I wanna this when user choose a AutoComplete location (h)ttp://www.imagesforme.com/show.php/1093307_CopyofSNAG0001.jpg (remove () on the beggining) Complete Code package com.svebee.prijevoz; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.TextView; public class ZelimDoci extends Activity { TextView lista; static final String[] STANICE = new String[] { "New York", "Chicago", "Dallas", "Los Angeles" }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.zelimdoci); AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, STANICE); textView.setAdapter(adapter); lista = (TextView)findViewById(R.id.lista); SQLiteDatabase myDB= null; String TableName = "Database"; String Data=""; /* Create a Database. */ try { myDB = this.openOrCreateDatabase("Database", MODE_PRIVATE, null); /* Create a Table in the Database. */ myDB.execSQL("CREATE TABLE IF NOT EXISTS " + TableName + " (Field1 INT(3) UNIQUE, Field2 INT(3) UNIQUE, Field3 VARCHAR UNIQUE, Field4 VARCHAR UNIQUE);"); Cursor a = myDB.rawQuery("SELECT * FROM Database where Field1 == 1", null); a.moveToFirst(); if (a == null) { /* Insert data to a Table*/ myDB.execSQL("INSERT INTO " + TableName + " (Field1, Field2, Field3, Field4)" + " VALUES (1, 119, 'New York', 'Dallas');"); myDB.execSQL("INSERT INTO " + TableName + " (Field1, Field2, Field3, Field4)" + " VALUES (9, 587, 'California', 'New York');"); } myDB.execSQL("INSERT INTO " + TableName + " (Field1, Field2, Field3, Field4)" + " VALUES (87, 57, 'Canada', 'London');"); } /*retrieve data from database */ Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null); int Column1 = c.getColumnIndex("Field1"); int Column2 = c.getColumnIndex("Field2"); int Column3 = c.getColumnIndex("Field3"); int Column4 = c.getColumnIndex("Field4"); // Check if our result was valid. c.moveToFirst(); if (c != null) { // Loop through all Results do { String LocationA = c.getString(Column3); String LocationB = c.getString(Column4); int Id = c.getInt(Column1); int Linija = c.getInt(Column2); Data =Data +Id+" | "+Linija+" | "+LocationA+"-"+LocationB+"\n"; }while(c.moveToNext()); } lista.setText(String.valueOf(Data)); } catch(Exception e) { Log.e("Error", "Error", e); } finally { if (myDB != null) myDB.close(); } } } .xml file <?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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="20sp" android:gravity="center_horizontal" android:padding="10sp" android:text="Test AutoComplete"/> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="5dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="AutoComplete" /> <AutoCompleteTextView android:id="@+id/autocomplete_country" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp"/> </LinearLayout> </LinearLayout>

    Read the article

  • How do I create an instance of this class in Android?

    - by Lloyd Banks
    I was wondering if it is possible to create an instance of this class (from the link, which creates a listview) from another class so that I can call on either lazyadapter.java or customizedlistview.java (not sure which one) to inflate that same listview. Is this possible? This is what I tried (obviously incorrect): CustomizedListView clv = new CustomizedListView(); clv.onCreate(...); source: http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/ LazyAdapter.java import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class LazyAdapter extends BaseAdapter { private Activity activity; private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyAdapter(Activity a, ArrayList&lt;HashMap&lt;String, String&gt;&gt; d) { activity = a; data=d; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader=new ImageLoader(activity.getApplicationContext()); } public int getCount() { return data.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.list_row, null); TextView title = (TextView)vi.findViewById(R.id.title); // title TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name TextView duration = (TextView)vi.findViewById(R.id.duration); // duration ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image HashMap&lt;String, String&gt; song = new HashMap&lt;String, String&gt;(); song = data.get(position); // Setting all values in listview title.setText(song.get(CustomizedListView.KEY_TITLE)); artist.setText(song.get(CustomizedListView.KEY_ARTIST)); duration.setText(song.get(CustomizedListView.KEY_DURATION)); imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image); return vi; } } CustomizedListView.java import java.util.ArrayList; import java.util.HashMap; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; public class CustomizedListView extends Activity { // All static variables static final String URL = "http://api.androidhive.info/music/music.xml"; // XML node keys static final String KEY_SONG = "song"; // parent node static final String KEY_ID = "id"; static final String KEY_TITLE = "title"; static final String KEY_ARTIST = "artist"; static final String KEY_DURATION = "duration"; static final String KEY_THUMB_URL = "thumb_url"; ListView list; LazyAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ArrayList&lt;HashMap&lt;String, String&gt;&gt; songsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(URL); // getting XML from URL Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_SONG); // looping through all song nodes &lt;song&gt; for (int i = 0; i &lt; nl.getLength(); i++) { // creating new HashMap HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); Element e = (Element) nl.item(i); // adding each child node to HashMap key =&gt; value map.put(KEY_ID, parser.getValue(e, KEY_ID)); map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE)); map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST)); map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION)); map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL)); // adding HashList to ArrayList songsList.add(map); } list=(ListView)findViewById(R.id.list); // Getting adapter by passing xml data ArrayList adapter=new LazyAdapter(this, songsList); list.setAdapter(adapter); // Click event for single list row list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { } }); } }

    Read the article

  • Android UnknownHost in asyncTask - loading web page

    - by Sneha
    I followed this tutorial for AsyncTask and getting the following error log: 03-23 11:44:42.936: WARN/System.err(315): java.net.UnknownHostException: www.google.co.in 03-23 11:44:42.936: WARN/System.err(315): at java.net.InetAddress.lookupHostByName(InetAddress.java:513) 03-23 11:44:42.936: WARN/System.err(315): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:278) 03-23 11:44:42.936: WARN/System.err(315): at java.net.InetAddress.getAllByName(InetAddress.java:242) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 03-23 11:44:42.936: WARN/System.err(315): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 03-23 11:44:42.944: WARN/System.err(315): at org.apache.http.impl.client.AbstractHttpC lient.execute(AbstractHttpClient.java:465) 03-23 11:44:42.944: WARN/System.err(315): at com.test.async.AsyncTaskExampleActivity$DownloadWebPageTask.doInBackground (AsyncTaskExampleActivity.java:36) 03-23 11:44:42.944: WARN/System.err(315): at com.test.async.AsyncTaskExampleActivity$DownloadWebPageTask.doInBackground (AsyncTaskExampleActivity.java:1) 03-23 11:44:42.944: WARN/System.err(315): at android.os.AsyncTask$2.call(AsyncTask.java:185) 03-23 11:44:42.944: WARN/System.err(315): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 03-23 11:44:42.944: WARN/System.err(315): at java.util.concurrent.FutureTask.run (FutureTask.java:137) 03-23 11:44:42.944: WARN/System.err(315): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 03-23 11:44:42.944: WARN/System.err(315): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 03-23 11:44:42.944: WARN/System.err(315): at java.lang.Thread.run(Thread.java:1096) How do i fix it?? My Code: public class AsyncTaskExampleActivity extends Activity { private TextView textView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.TextView01); } private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String response = ""; Log.i("", "in doInBackgroundddddddddd.........."); Log.i("", "in readWebpageeeeeeeeeeeee"); /* * try { InetAddress i = * InetAddress.getByName("http://google.co.in"); } catch * (UnknownHostException e1) { e1.printStackTrace(); } */ for (String url : urls) { Log.i("", "in for looooooop doInBackgroundddddddddd.........."); DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { Log .i("", "afetr for looooooop try doInBackgroundddddddddd.........."); HttpResponse execute = client.execute(httpGet); Log .i("", "afetr for looooooop try client ..execute doInBackgroundddddddddd.........."); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader( new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; Log .i("", "afetr while looooooop try client ..execute doInBackgroundddddddddd.........."); } } catch (Exception e) { e.printStackTrace(); } } Log .i("", "afetr lasttttttttttttt b4 response doInBackgroundddddddddd.........."); return response; } @Override protected void onPostExecute(String result) { Log.i("", "in onPostExecuteeee.........."); textView.setText(result); } } public void readWebpage(View view) { /* * System.setProperty("http.proxyHost", "10.132.116.10"); * System.setProperty("http.proxyPort", "3128"); */ DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "http://google.co.in" }); Log.i("", "in readWebpageeeeeeeeeeeee after execute.........."); } } main.xml: <Button android:id="@+id/readWebpage" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="readWebpage" android:text="Load Webpage"> </Button> <TextView android:id="@+id/TextView01" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Example Text"> </TextView> Manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.test.async" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".AsyncTaskExampleActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> Thanks Sneha

    Read the article

  • how to save state of dynamically created editTexts

    - by user922531
    I'm stuck at how to save the state of my EditTexts on screen orientation. Currently if text is inputted into the EditTexts and the screen is orientated, the fields are wiped (as expected). I am already calling onSaveInstanceState and saving a String, but I have no clue on how to save the EditTexts which are created in code and then retrieve them and add them to the EditTexts when redrawing the activity. Snippet of my code: My main activity is as follows: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // get the multidim array b = getIntent().getBundleExtra("obj"); m = (Methods) b.getSerializable("Methods"); // method to draw the layout InitialiseUI(); // Restore UI state from the savedInstanceState. if (savedInstanceState != null) { String strValue = savedInstanceState.getString("light"); if (strValue != null) { FLight = strValue; } } try { mCamera = Camera.open(); if (FLight.equals("true")) { flashLight(); } } catch (Exception e) { Log.d(TAG, "Thrown exception onCreate() camera: " + e); } } // end onCreate /** Called when the back button is pressed. */ @Override public void onResume() { super.onResume(); try { mCamera = Camera.open(); if (FLight.equals("true")) { flashLight(); } } catch (Exception e) { Log.d(TAG, "Thrown exception onCreate() camera: " + e); } } // end onCreate /** saves data before leaving the screen */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("light", FLight); } /** called when exiting / leaving the screen */ @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause()"); if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; } } /* * set up the UI elements - add click listeners to buttons used in * onCreate() and onConfigurationChanged() * * Set the editTexts fields to show the previous readings as Hints */ public void InitialiseUI() { Log.d(TAG, "Start of InitialiseUI, Main activity"); // get a reference to the TableLayout final TableLayout myTLreads = (TableLayout) findViewById(R.id.myTLreads); // Create arrays to hold the TVs and ETs final TextView[] myTextViews = new TextView[m.getNoRows()]; // create an empty array; final EditText[] myEditTexts = new EditText[m.getNoRows()]; // create an empty array; for(int i =0; i<=m.getNoRows()-1;i++ ){ TableRow tr=new TableRow(this); tr.setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); // create a new textview / editText final TextView rowTextView = new TextView(this); final EditText rowEditText = new EditText(this); // setWidth is needed otherwise my landscape layout is OFF rowEditText.setWidth(400); // this stops the keyboard taking up the whole screen in landscape layout rowEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); // add some padding to the right of the TV rowTextView.setPadding(0,0,10,0); // set colors to white rowTextView.setTextColor(Color.parseColor("#FFFFFF")); rowEditText.setTextColor(Color.parseColor("#FFFFFF")); // if readings already sent today set color to yellow if(m.getTransmit(i+1)==false){ rowEditText.setEnabled(false); rowEditText.setHintTextColor(Color.parseColor("#FFFF00")); } // set the text of the TV to the meter name rowTextView.setText(m.getMeterName(i+1)); // set the hint of the ET to the last submitted reading rowEditText.setHint(m.getLastReadString(i+1)); // add the textview to the linearlayout rowEditText.setInputType(InputType.TYPE_CLASS_PHONE);//InputType.TYPE_NUMBER_FLAG_DECIMAL); tr.addView(rowTextView); tr.addView(rowEditText); myTLreads.addView(tr); // add a reference to the textView myTextViews[i] = rowTextView; myEditTexts[i] = rowEditText; } final Button submit = (Button) findViewById(R.id.submitReadings); // add a click listener to the button try { submit.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "Submit button clicked, Main activity"); preSubmitCheck(m.getAccNo(), m.getPostCode(), myEditTexts); // method to do HTML getting and sending } }); } catch (Exception e) { Log.d(TAG, "Exceptions (submit button)" + e.toString()); } }// end of InitialiseUI I don't need to do anything with these values until a button is clicked. Would it be easier if they were a ListView, i'm guessing I would still have the problem of saving them and retrieving them on rotation. If it helps I have an object m which is a string[][] I could temporarily somehow store them in

    Read the article

  • How do you set Android ViewPager to encompass only one View or Layout?

    - by Kyle
    I am struggling with the concepts needed to properly implement a view pager. By following some tutorials and referencing developer.android.com, I am able to get a view pager almost fully functional. The pager will flip through several text views that have been setup to say "My Message 0" through "My Message 9". The problem is that the view pager also flips the button on the bottom of the activity and the red block that is right above the button. I would like to have the view pager only cycle through the text. Would you please help me understand what I'm doing wrong? I have an activity that represents a dashboard: public class DashBoard extends FragmentActivity { private static final int NUMBER_OF_PAGES = 10; private ViewPager mViewPager; private MyFragmentPagerAdapter mMyFragmentPagerAdapter; public void onCreate(Bundle icicle){ super.onCreate(icicle); setContentView(R.layout.dashboard); mViewPager = (ViewPager) findViewById(R.id.viewpager); mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager()); mViewPager.setAdapter(mMyFragmentPagerAdapter); } private static class MyFragmentPagerAdapter extends FragmentPagerAdapter{ public MyFragmentPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int index) { return PageFragment.newInstance("My Message " + index); } @Override public int getCount(){ return NUMBER_OF_PAGES; } } and a class for the page fragment: public class PageFragment extends Fragment { public static PageFragment newInstance(String title){ PageFragment pageFragment = new PageFragment(); Bundle bundle = new Bundle(); bundle.putString("title", title); pageFragment.setArguments(bundle); return pageFragment; } @Override public void onCreate(Bundle icicle){ super.onCreate(icicle); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle icicle){ View view = inflater.inflate(R.layout.dashboard, container, false); TextView textView = (TextView) view.findViewById(R.id.textViewPage); textView.setText(getArguments().getString("title")); return view; } } and finally, my xml for the dashboard: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/dashbaordLabel" android:layout_width="match_parent" android:layout_height="wrap_content" > <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" /> <TextView android:id="@+id/textViewPage" android:layout_width = "match_parent" android:layout_height= "wrap_content" /> <Button android:id="@+id/newGoalButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/stringNewGoal" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:onClick="createNewGoal" /> <RelativeLayout android:id="@+id/SpaceBottom" android:layout_width="match_parent" android:layout_height="75dp" android:layout_above="@id/newGoalButton" android:background="@color/red" > </RelativeLayout> </RelativeLayout> A note about my xml, I tried wrapping the text view in some view pager tags eg: <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" > <TextView android:id="@+id/textViewPage" android:layout_width = "match_parent" android:layout_height= "wrap_content" /> </android.support.v4.view.ViewPager> But all that did was make the text view disappear from the screen, while the button and red block still cycled as in the original issue.

    Read the article

  • How do I make this scroll layout work?

    - by JuiCe
    I am currently trying to get my UI to have a Title Bar, a bottom Button bar, with a ScrollView in between. I can get bits and pieces of it to work, but once I get a different piece working, the old part goes back to not showing up. Here is a picture of my UI on the left, with what I want it to look like on the right...(sorry for the sloppiness, I edited it in MS Paint :P ) To sum it up, I want the Version and Type fields to be moved with room for the other TextViews in the XML file, and I want both buttons to appear on the bottom bar. EDIT : The buttons on the bottom should be equal in size, I'm not too talented in making boxes in MS Paint EDIT 2 : Sorry....here is my 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" android:weightSum="1.0" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="SN : " /> <TextView android:id="@+id/serialNumberView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="Ver : " /> <TextView android:id="@+id/versionView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="Type : " /> <TextView android:id="@+id/typeView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal" /> </LinearLayout> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="1"> <CheckBox android:id="@+id/floatCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Float" /> <CheckBox android:id="@+id/tripCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Trip" /> <CheckBox android:id="@+id/closeCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Close" /> <CheckBox android:id="@+id/blockedCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Blocked" /> <CheckBox android:id="@+id/hardTripCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hard Trip" /> <CheckBox android:id="@+id/phaseAngleCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Phase angle wrong for closing" /> <CheckBox android:id="@+id/diffVoltsCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Differential volts too low" /> <CheckBox android:id="@+id/networkVoltsCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Network volts too low to close" /> <CheckBox android:id="@+id/usingDefaultsCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Using Defaults( Reprogram )" /> <CheckBox android:id="@+id/relaxedCloseActiveCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Relaxed Close Active" /> <CheckBox android:id="@+id/commBoardDetectedCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Comm Board Detected" /> <CheckBox android:id="@+id/antiPumpBlock" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Anti-Pump Block" /> <CheckBox android:id="@+id/motorCutoffCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Motor Cutoff Inhibit" /> <CheckBox android:id="@+id/phaseRotationCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Phase Rotation Wrong" /> <CheckBox android:id="@+id/usingDefaultDNPCheck" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text= "Using Default DNP Profile" /> </LinearLayout> </ScrollView> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_weight="1" > <Button android:id="@+id/button3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Back" /> <Button android:id="@+id/button3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Read" /> </LinearLayout> </LinearLayout>

    Read the article

  • SurfaceView drawn on top of other elements after coming back from specific activity

    - by spirytus
    I have an activity with video preview displayed via SurfaceView and other views positioned over it. The problem is when user navigates to Settings activity (code below) and comes back then the surfaceview is drawn on top of everything else. This does not happen when user goes to another activity I have, neither when user navigates outside of app eg. to task manager. Now, you see in code below that I have setContentVIew() call wrapped in conditionals so it is not called every time when onStart() is executed. If its not wrapped in if statements then all works fine, but its causing loosing lots of memory (5MB+) each time onStart() is called. I tried various combinations and nothing seems to work so any help would be much appreciated. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Toast.makeText(this,"Create ", 2000).show(); // set 32 bit window (draw correctly transparent images) getWindow().getAttributes().format = android.graphics.PixelFormat.RGBA_8888; // set the layout of the screen based on preferences of the user sharedPref = PreferenceManager.getDefaultSharedPreferences(this); } public void onStart() { super.onStart(); String syncConnPref = null; syncConnPref = sharedPref.getString("screensLayouts", "default"); if(syncConnPref.contentEquals("default") && currentlLayout!="default") { setContentView(R.layout.fight_recorder_default); } else if(syncConnPref.contentEquals("simple") && currentlLayout!="simple") { setContentView(R.layout.fight_recorder_simple); } // I I uncomment line below so it will be called every time without conditionals above, it works fine but every time onStart() is called I'm losing 5+ MB memory (memory leak?). The preview however shows under the other elements exactly as I need memory leak makes it unusable after few times though // setContentView(R.layout.fight_recorder_default); if(getCamera()==null) { Toast.makeText(this,"Sorry, camera is not available and fight recording will not be permanently stored",2000).show(); // TODO also in here put some code replacing the background with something nice return; } // now we have camera ready and we need surface to display picture from camera on so // we instantiate CameraPreviw object which is simply surfaceView containing holder object. // holder object is the surface where the image will be drawn onto // this is where camera live cameraPreview will be displayed cameraPreviewLayout = (FrameLayout) findViewById(id.camera_preview); cameraPreview = new CameraPreview(this); // now we add surface view to layout cameraPreviewLayout.removeAllViews(); cameraPreviewLayout.addView(cameraPreview); // get layouts prepared for different elements (views) // this is whole recording screen, as big as screen available recordingScreenLayout=(FrameLayout) findViewById(R.id.recording_screen); // this is used to display sores as they are added, it displays like a path // each score added is a new text view simply and as user undos these are removed one by one allScoresLayout=(LinearLayout) findViewById(R.id.all_scores); // layout prepared for controls like record/stop buttons etc startStopLayout=(RelativeLayout) findViewById(R.id.start_stop_layout); // set up timer so it can be turned on when needed //fightTimer=new FightTimer(this); fightTimer = (FightTimer) findViewById(id.fight_timer); // get views for displaying scores score1=(TextView) findViewById(id.score1); score2=(TextView) findViewById(id.score2); advantages1=(TextView) findViewById(id.advantages1); advantages2=(TextView) findViewById(id.advantages2); penalties1=(TextView) findViewById(id.penalties1); penalties2=(TextView) findViewById(id.penalties2); RelativeLayout welcomeScreen=(RelativeLayout) findViewById(id.welcome_screen); Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in); welcomeScreen.startAnimation(fadeIn); Toast.makeText(this,"Start ", 2000).show(); animateViews(); } Settings activity is below, after coming back from this activity surfaceview is drawn on top of other elements. public class SettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(MyFirstAppActivity.getCamera()==null) { Toast.makeText(this,"Sorry, camera is not available",2000).show(); return; } addPreferencesFromResource(R.xml.preferences); } }

    Read the article

  • How to make condition inside getView of Custom BaseAdapter

    - by user1501150
    I want to make a Custom ListView with Custom BaseAdapter, where the the status=1,I want to show a CheckBox, and else I want to show a textView.. My given condition is: if (NewtheStatus == 1) { alreadyOrderText .setVisibility(TextView.GONE); } else{ checkBox.setVisibility(CheckBox.GONE); } But Some times I obtain some row that has neither checkBox nor TextView. The Code of my Custom BaseAdapter is given below . private class MyCustomAdapter extends BaseAdapter { private static final int TYPE_ITEM = 0; private static final int TYPE_ITEM_WITH_HEADER = 1; // private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1; private ArrayList<WatchListAllEntity> mData = new ArrayList(); private LayoutInflater mInflater; private ArrayList<WatchListAllEntity> items = new ArrayList<WatchListAllEntity>(); public MyCustomAdapter(Context context, ArrayList<WatchListAllEntity> items) { mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void addItem(WatchListAllEntity watchListAllEntity) { // TODO Auto-generated method stub items.add(watchListAllEntity); } public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; final int position1 = position; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.listitempict, null); } watchListAllEntity = new WatchListAllEntity(); watchListAllEntity = items.get(position); Log.i("position: iteamsLength ", position + ", " + items.size()); if (watchListAllEntity != null) { ImageView itemImage = (ImageView) v .findViewById(R.id.imageviewproduct); if (watchListAllEntity.get_thumbnail_image_url1() != null) { Drawable image = ImageOperations(watchListAllEntity .get_thumbnail_image_url1().replace(" ", "%20"), "image.jpg"); // itemImage.setImageResource(R.drawable.icon); if (image != null) { itemImage.setImageDrawable(image); itemImage.setAdjustViewBounds(true); } else { itemImage.setImageResource(R.drawable.iconnamecard); } Log.i("status_ja , status", watchListAllEntity.get_status_ja() + " ," + watchListAllEntity.getStatus()); int NewtheStatus = Integer.parseInt(watchListAllEntity .getStatus()); CheckBox checkBox = (CheckBox) v .findViewById(R.id.checkboxproduct); TextView alreadyOrderText = (TextView) v .findViewById(R.id.alreadyordertext); if (NewtheStatus == 1) { alreadyOrderText .setVisibility(TextView.GONE); } else{ checkBox.setVisibility(CheckBox.GONE); } Log.i("Loading ProccardId: ", watchListAllEntity.get_proc_card_id() + ""); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { WatchListAllEntity watchListAllEntity2 = items .get(position1); Log.i("Position: ", position1 + ""); // TODO Auto-generated method stub if (isChecked) { Constants.orderList.add(watchListAllEntity2 .get_proc_card_id()); Log.i("Proc Card Id Add: ", watchListAllEntity2 .get_proc_card_id() + ""); } else { Constants.orderList.remove(watchListAllEntity2 .get_proc_card_id()); Log.i("Proc Card Id Remove: ", watchListAllEntity2.get_proc_card_id() + ""); } } }); } } return v; } private Drawable ImageOperations(String url, String saveFilename) { try { InputStream is = (InputStream) this.fetch(url); Drawable d = Drawable.createFromStream(is, "src"); return d; } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } } public Object fetch(String address) throws MalformedURLException, IOException { URL url = new URL(address); Object content = url.getContent(); return content; } public int getCount() { // TODO Auto-generated method stub int sizef=items.size(); Log.i("Size", sizef+""); return items.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return items.get(position); } public long getItemId(int position) { // TODO Auto-generated method stub return position; } }

    Read the article

  • Android -- autoLink

    - by Ryan
    Is there any way to Linkify a specific TextView that is contained within a ListView? I tried using android:autoLink="all" but that didn't work. I was getting an out of context error. Important also to note: the ListView is my second view in the ViewFlipper. I have also tried: View mItemView = mAdapter.getView(2, null, null); TextView infoText = (TextView) mItemView.findViewById(R.id.rowText2); Linkify.addLinks(infoText, Linkify.ALL); Right after the adapter was bound to the ListView and the View was switched. No luck. Here is the stack trace: 06-03 21:19:25.180: ERROR/AndroidRuntime(1214): Uncaught handler: thread main exiting due to uncaught exception 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.app.ApplicationContext.startActivity(ApplicationContext.java:550) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.content.ContextWrapper.startActivity(ContextWrapper.java:248) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.text.style.URLSpan.onClick(URLSpan.java:62) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.text.method.LinkMovementMethod.onTouchEvent(LinkMovementMethod.java:216) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.widget.TextView.onTouchEvent(TextView.java:6560) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.view.View.dispatchTouchEvent(View.java:3709) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.app.Activity.dispatchTouchEvent(Activity.java:2061) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.os.Handler.dispatchMessage(Handler.java:99) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.os.Looper.loop(Looper.java:123) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at android.app.ActivityThread.main(ActivityThread.java:4363) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at java.lang.reflect.Method.invokeNative(Native Method) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at java.lang.reflect.Method.invoke(Method.java:521) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 06-03 21:19:25.219: ERROR/AndroidRuntime(1214): at dalvik.system.NativeStart.main(Native Method) Any Ideas? Thanks in advance!!!

    Read the article

  • ExpandableListView child items don't get focus when touched...

    - by Justin
    Ok, so I wrote an ExpandableListView and subclassed BaseExpandableListAdapter... Everything works fine except I cannot get the child views to take focus when clicked. If I use the trackball everything works fine. But if I try to click on a child I get no feedback whatsoever. I have tried setting android:focusable, android:focusableInTouchMode, and android:clickable (and I have also tried setting this via code) but I can't get anything to work. Any ideas? Here is my Adapter code: public class ExpandableAppAdapter extends BaseExpandableListAdapter { private PackageManager m_pkgMgr; private Context m_context; private List<ApplicationInfo> m_groups; private List<List<ComponentName>> m_children; public ExpandableAppAdapter(Context context, List<ApplicationInfo> groups, List<List<ComponentName>> children) { m_context = context; m_pkgMgr = m_context.getPackageManager(); m_groups = groups; m_children = children; } @Override public Object getChild(int groupPos, int childPos) { return m_children.get(groupPos).get(childPos); } @Override public long getChildId(int groupPos, int childPos) { return childPos; } @Override public int getChildrenCount(int groupPos) { return m_children.get(groupPos).size(); } @Override public View getChildView(int groupPos, int childPos, boolean isLastChild, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(m_context); convertView = inflater.inflate(R.layout.expandable_app_child_row, null); } ComponentName child = (ComponentName)getChild(groupPos, childPos); TextView txtView = (TextView)convertView.findViewById(R.id.item_app_pkg_name_id); if (txtView != null) txtView.setText(child.getPackageName()); txtView = (TextView)convertView.findViewById(R.id.item_app_class_name_id); if (txtView != null) txtView.setText(child.getClassName()); convertView.setFocusableInTouchMode(true); return convertView; } @Override public Object getGroup(int groupPos) { return m_groups.get(groupPos); } @Override public int getGroupCount() { return m_groups.size(); } @Override public long getGroupId(int groupPos) { return groupPos; } @Override public View getGroupView(int groupPos, boolean isExpanded, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(m_context); convertView = inflater.inflate(R.layout.expandable_app_group_row, null); } ApplicationInfo group = (ApplicationInfo)getGroup(groupPos); ImageView imgView = (ImageView)convertView.findViewById(R.id.item_selection_icon_id); if (imgView != null) { Drawable img = m_pkgMgr.getApplicationIcon(group); imgView.setImageDrawable(img); imgView.setMaxWidth(20); imgView.setMaxHeight(20); } TextView txtView = (TextView)convertView.findViewById(R.id.item_app_name_id); if (txtView != null) txtView.setText(m_pkgMgr.getApplicationLabel(group)); return convertView; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPos, int childPos) { return true; } } Thanks in advance!

    Read the article

  • LinearLayout - How to get text to be on the right of an icon?

    - by RED_
    Hi there, Bit of a newbie when it comes to android, only been working on it properly for a few days but even after all the searching I've done im stumped and nobody seems to know how to help me. I have this so far: http://img263.imageshack.us/i/sellscreen.jpg How can I move the text to be besides each icon rather than underneath it? Hoping the gallery won't be moved either. Here is the code i have: <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Gallery xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions." /> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions."/> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions."/> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions."/> <ImageView android:id="@+id/test_image" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="The offcial UK driving theory test application. Over 190 questions." /> </LinearLayout> </ScrollView> Top half of my code doesn't seem to be showing for some reason but it's just the opening of the linear layout. I will be forever grateful to anyone that can help, i've been racking my brains for days and getting nowhere. Really getting stressed out by it. Thanks in advance!!

    Read the article

  • Large margin by long title

    - by Kevin Koenen
    I try to show a list of offers. When an advertiser insert a large title, the margin of an item (offer) will be showed what shouldn't. I've tried different layouts but that doesn't work. Link to image :) You see, some of the items has a large margin. Here's the code: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gallerylayout" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:gravity="left|center" android:layout_width="wrap_content" android:paddingBottom="2dp" android:paddingTop="2dp" android:paddingLeft="5dp" android:background="#20000000" android:cacheColorHint="#00000000"> <ImageView android:id="@+id/ad_image_small" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="6dip" android:src="@drawable/ic_launcher"/> <LinearLayout android:orientation="vertical" android:layout_width="0dip" android:layout_weight="1" android:layout_height="fill_parent"> <TextView android:id="@+id/ad_id" android:visibility="gone" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/ad_img_url" android:visibility="gone" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/ad_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="3dp" android:gravity="left" android:textColor="#000000" android:ellipsize="end" android:singleLine="true"/> <TextView android:id="@+id/ad_km" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="3dp" android:layout_marginBottom="1dp" android:textColor="#000000" android:gravity="right"/> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/ad_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="3dp" android:textColor="#0099CC" android:ellipsize="end" android:singleLine="true"/> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:padding="5dp"> <ImageView android:id="@+id/ad_clock" android:layout_width="20dp" android:layout_height="20dp" android:layout_marginRight="5dip" android:src="@drawable/icon_clock"/> <ProgressBar android:id="@+id/progressbar" android:layout_width="match_parent" android:layout_height="8dp" android:layout_margin="5dp" android:paddingLeft="2dp" android:max="100" style="?android:attr/progressBarStyleHorizontal" android:progressDrawable="@drawable/color_progressbar" /> </LinearLayout> </LinearLayout> </LinearLayout> <ImageView android:id="@+id/overlay_image" android:background="#0000" android:src="@drawable/verlopen2x" android:layout_alignTop="@id/ad_image_small" android:layout_alignBottom="@id/ad_image_small" android:layout_width="fill_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:visibility="visible" /> I can't see what i'm doing wrong. Thanks in advance!

    Read the article

  • Creating a ListView and setting the background color of a view in each row.

    - by Tarmon
    Hey Everyone, I am trying to implement a ListView that is composed of rows that contain a View on the left followed by a TextView to the right of that. I want to be able to change the background color of the first View based on it's position in the ListView. Below is what I have at this point but it doesn't seem to due anything. public class Routes extends ListActivity { String[] ROUTES; TextView selection; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ROUTES = getResources().getStringArray(R.array.routes); setContentView(R.layout.routes); setListAdapter(new IconicAdapter()); selection=(TextView)findViewById(R.id.selection); } public void onListItemClick(ListView parent, View v, int position, long id) { selection.setText(ROUTES[position]); } class IconicAdapter extends ArrayAdapter<String> { IconicAdapter() { super(Routes.this, R.layout.row, R.id.label, ROUTES); } } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.row, parent, false); TextView label = (TextView) row.findViewById(R.id.label); label.setText(ROUTES[position]); View icon = (View) row.findViewById(R.id.icon); switch(position){ case 0: icon.setBackgroundColor(R.color.Red); break; case 1: icon.setBackgroundColor(R.color.Red); break; case 2: icon.setBackgroundColor(R.color.Green); break; case 3: icon.setBackgroundColor(R.color.Green); break; case 4: icon.setBackgroundColor(R.color.Blue); break; case 5: icon.setBackgroundColor(R.color.Blue); break; } return(row); } } Any input is appreciated and if you have any questions don't hesitate to ask! Thanks, Rob

    Read the article

  • Simple reminder for Android

    - by anta40
    I'm trying to make a simple timer. package com.anta40.reminder; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.widget.RadioGroup; import android.widget.TabHost; import android.widget.TextView; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TabHost.TabSpec; public class Reminder extends Activity{ public final int TIMER_DELAY = 1000; public final int TIMER_ONE_MINUTE = 60000; public final int TIMER_ONE_SECOND = 1000; Timer timer; TimerTask task; TextView tv; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); timer = new Timer(); task = new TimerTask() { @Override public void run() { tv = (TextView) findViewById(R.id.textview1); tv.setText("BOOM!!!!"); tv.setVisibility(TextView.VISIBLE); try { this.wait(TIMER_DELAY); } catch (InterruptedException e){ } tv.setVisibility(TextView.INVISIBLE); } }; TabHost tabs=(TabHost)findViewById(R.id.tabhost); tabs.setup(); TabSpec spec = tabs.newTabSpec("tag1"); spec.setContent(R.id.tab1); spec.setIndicator("Clock"); tabs.addTab(spec); spec=tabs.newTabSpec("tag2"); spec.setContent(R.id.tab2); spec.setIndicator("Settings"); tabs.addTab(spec); tabs.setCurrentTab(0); RadioGroup rgroup = (RadioGroup) findViewById(R.id.rgroup); rgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.om){ timer.schedule(task, TIMER_DELAY, 3*TIMER_ONE_SECOND); } else if (checkedId == R.id.twm){ timer.schedule(task, TIMER_DELAY, 6*TIMER_ONE_SECOND); } else if (checkedId == R.id.thm){ timer.schedule(task, TIMER_DELAY, 9*TIMER_ONE_SECOND); } } }); } } Each time I click a radio button, the timer should start, right? But why it doesn't start?

    Read the article

  • Android Expandable List View Update

    - by Gaurav Arora
    I am implementing a chatting application, where I have made a service to listen all the presence changed. On the change of the presence I want to update the data and I am unable to update the data that is showing in the expandable list view. Please suggest me a means to do the same. public class UserMenuActivity extends ExpandableListActivity { private XMPPConnection connection; String name,availability,subscriptionStatus; TextView tv_Status; /** Variable Define here */ private String[] data = { "View my profile", "New Multiperson Chat", "New Broad Cast Message", "New Contact Category", "New Group", "Invite to CCM", "Search", "Expand All", "Settings", "Help", "Close" }; private String[] data_Contact = { "Rename Category","Move Contact to Category", "View my profile", "New Multiperson Chat", "New Broad Cast Message", "New Contact Category", "New Group", "Invite to CCM", "Search", "Expand All", "Settings", "Help", "Close" }; private String[] data_child_contact = { "Open chat", "Delete Contact","View my profile", "New Multiperson Chat", "New Broad Cast Message", "New Contact Category", "New Group", "Invite to CCM", "Search", "Expand All", "Settings", "Help", "Close" }; private String[] menuItem = { "Chats", "Contacts", "CGM Groups", "Pending","Request" }; private List<String> menuItemList = Arrays.asList(menuItem); private int commonGroupPosition = 0; private String etAlertVal; private DatabaseHelper dbHelper; private int categoryID, listPos; /** New Code here.. */ private ArrayList<String> groupNames; private ArrayList<ArrayList<ChildItems>> childs; private UserMenuAdapter adapter; private Object object; private String[] data2 = { "PIN Michelle", "IP Call" }; private ListView mlist2; private ImageButton mimBtnMenu; private LinearLayout mllpopmenu; private View popupView; private PopupWindow popupWindow; private AlertDialog.Builder alert; private EditText input; private TextView mtvUserName, mtvUserTagLine; private ExpandableListView mExpandableListView; public static List<CategoryDataClass> categoryList; private boolean menuType = false; private String childValContact=""; public static Context context; @Override public void onBackPressed() { if (mllpopmenu.getVisibility() == View.VISIBLE) { mllpopmenu.setVisibility(View.INVISIBLE); } else { if (CCMStaticVariable.CommonConnection.isConnected()) { CCMStaticVariable.CommonConnection.disconnect(); } super.onBackPressed(); } } @SuppressWarnings("unchecked") @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (mllpopmenu.getVisibility() == View.VISIBLE) { mllpopmenu.setVisibility(View.INVISIBLE); } else { if (commonGroupPosition >= 4 && menuType == true) { if(childValContact == ""){ mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data_Contact)); }else{ mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data_child_contact)); } } else if (commonGroupPosition == 0) { mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data)); } } return true; } return super.onKeyDown(keyCode, event); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.usermenulayout); dbHelper = new DatabaseHelper(UserMenuActivity.this); //this.context = context.getApplicationContext(); XMPPConn.getContactList(); connection = CCMStaticVariable.CommonConnection; Presence userPresence = new Presence(Presence.Type.available); userPresence.setPriority(24); userPresence.setMode(Presence.Mode.away); connection.sendPacket(userPresence); } @Override protected void onResume() { super.onResume(); Presence userPresence = new Presence(Presence.Type.available); userPresence.setPriority(24); userPresence.setMode(Presence.Mode.away); connection.sendPacket(userPresence); XMPPConn.getContactList(); setExpandableListView(); } public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { if (groupPosition == 1 && childPosition == 0) { startActivity(new Intent(UserMenuActivity.this, InvitetoCCMActivity.class)); } else if (groupPosition == 1 && childPosition != 0) { Intent intent = new Intent(UserMenuActivity.this, UserChatActivity.class); intent.putExtra("userNameVal", XMPPConn.mfriendList.get(childPosition - 1).friendName); startActivity(intent); } else if (groupPosition == 2 && childPosition == 0) { startActivity(new Intent(UserMenuActivity.this, CreateGroupActivity.class)); } else if (groupPosition == 2 && childPosition != 0) { String GROUP_NAME = childs.get(groupPosition).get(childPosition) .getName().toString(); int end = GROUP_NAME.indexOf("("); CCMStaticVariable.groupName = GROUP_NAME.substring(0, end).trim(); startActivity(new Intent(UserMenuActivity.this, GroupsActivity.class)); } else if (groupPosition >= 4) { childValContact = childs.get(groupPosition).get(childPosition).getName().trim(); showToast("user==>"+childValContact, 0); } return false; } private void setExpandableListView() { /***###############GROUP ARRAY ############################*/ final ArrayList<String> groupNames = new ArrayList<String>(); groupNames.add("Chats (2)"); groupNames.add("Contacts (" + XMPPConn.mfriendList.size() + ")"); groupNames.add("CGM Groups (" + XMPPConn.mGroupList.size() + ")"); groupNames.add("Pending (1)"); XMPPConn.getGroup(); categoryList = dbHelper.getAllCategory(); /**Group From Sever*/ if (XMPPConn.mGroupList.size() > 0) { for (int g = 0; g < XMPPConn.mGroupList.size(); g++) { XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName); groupNames.add(XMPPConn.mGroupList.get(g).groupName + "(" + XMPPConn.mGroupContactList.size()+ ")"); } } if(categoryList.size() > 0){ for (int cat = 0; cat < categoryList.size(); cat++) { groupNames.add(categoryList.get(cat).getCategoryName()+ "(0)"); } } this.groupNames = groupNames; /*** ###########CHILD ARRAY * #################*/ ArrayList<ArrayList<ChildItems>> childs = new ArrayList<ArrayList<ChildItems>>(); ArrayList<ChildItems> child = new ArrayList<ChildItems>(); child.add(new ChildItems("Alisha", "Hi",0)); child.add(new ChildItems("Michelle", "Good Morning",0)); childs.add(child); child = new ArrayList<ChildItems>(); child.add(new ChildItems("", "",0)); if (XMPPConn.mfriendList.size() > 0) { for (int n = 0; n < XMPPConn.mfriendList.size(); n++) { child.add(new ChildItems(XMPPConn.mfriendList.get(n).friendNickName, XMPPConn.mfriendList.get(n).friendStatus, XMPPConn.mfriendList.get(n).friendState)); } } childs.add(child); /************** CGM Group Child here *********************/ child = new ArrayList<ChildItems>(); child.add(new ChildItems("", "",0)); if (XMPPConn.mGroupList.size() > 0) { for (int grop = 0; grop < XMPPConn.mGroupList.size(); grop++) { child.add(new ChildItems( XMPPConn.mGroupList.get(grop).groupName + " (" + XMPPConn.mGroupList.get(grop).groupUserCount + ")", "",0)); } } childs.add(child); child = new ArrayList<ChildItems>(); child.add(new ChildItems("Shuchi", "Pending (Waiting for Authorization)",0)); childs.add(child); /************************ Group Contact List *************************/ if (XMPPConn.mGroupList.size() > 0) { for (int g = 0; g < XMPPConn.mGroupList.size(); g++) { /** Contact List */ XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName); child = new ArrayList<ChildItems>(); for (int con = 0; con < XMPPConn.mGroupContactList.size(); con++) { child.add(new ChildItems( XMPPConn.mGroupContactList.get(con).friendName, XMPPConn.mGroupContactList.get(con).friendStatus,0)); } childs.add(child); } } if(categoryList.size() > 0){ for (int cat = 0; cat < categoryList.size(); cat++) { child = new ArrayList<ChildItems>(); child.add(new ChildItems("-none-", "",0)); childs.add(child); } } this.childs = childs; /** Set Adapter here */ adapter = new UserMenuAdapter(this, groupNames, childs); setListAdapter(adapter); object = this; mlist2 = (ListView) findViewById(R.id.list2); mimBtnMenu = (ImageButton) findViewById(R.id.imBtnMenu); mllpopmenu = (LinearLayout) findViewById(R.id.llpopmenu); mtvUserName = (TextView) findViewById(R.id.tvUserName); mtvUserTagLine = (TextView) findViewById(R.id.tvUserTagLine); //Set User name.. System.out.println("CCMStaticVariable.loginUserName===" + CCMStaticVariable.loginUserName); if (!CCMStaticVariable.loginUserName.equalsIgnoreCase("")) { mtvUserName.setText("" + CCMStaticVariable.loginUserName); } /** Expandable List set here.. */ mExpandableListView = (ExpandableListView) this .findViewById(android.R.id.list); mExpandableListView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { XMPPConn.getContactList(); if (parent.isGroupExpanded(groupPosition)) { commonGroupPosition = 0; }else{ commonGroupPosition = groupPosition; } String GROUP_NAME = groupNames.get(groupPosition); int end = groupNames.get(groupPosition).indexOf("("); String GROUP_NAME_VALUE = GROUP_NAME.substring(0, end).trim(); if (menuItemList.contains(GROUP_NAME_VALUE)) { menuType = false; CCMStaticVariable.groupCatName = GROUP_NAME_VALUE; } else { menuType = true; CCMStaticVariable.groupCatName = GROUP_NAME_VALUE; } long findCatId = dbHelper.getCategoryID(GROUP_NAME_VALUE); if (findCatId != 0) { categoryID = (int) findCatId; } childValContact=""; showToast("Clicked on==" + GROUP_NAME_VALUE, 0); return false; } }); /** Click on item */ mlist2.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long arg3) { if (commonGroupPosition >= 4) { if(childValContact == ""){ if (pos == 0) { showAlertEdit(CCMStaticVariable.groupCatName); } /** Move contact to catgory */ if (pos == 1) { startActivity(new Intent(UserMenuActivity.this,AddContactCategoryActivity.class)); } }else{ if(pos == 0){ Intent intent = new Intent(UserMenuActivity.this,UserChatActivity.class); intent.putExtra("userNameVal",childValContact); startActivity(intent); } if(pos == 1){ XMPPConn.removeEntry(childValContact); showToast("Contact deleted sucessfully", 0); Intent intent = new Intent(UserMenuActivity.this,UserMenuActivity.class); } } } else { /** MyProfile */ if (pos == 0) { startActivity(new Intent(UserMenuActivity.this, MyProfileActivity.class)); } /** New multiperson chat start */ if (pos == 1) { startActivity(new Intent(UserMenuActivity.this, NewMultipersonChatActivity.class)); } /** New Broadcast message */ if (pos == 2) { startActivity(new Intent(UserMenuActivity.this, NewBroadcastMessageActivity.class)); } /** Click on add category */ if (pos == 3) { showAlertAdd(); } if (pos == 4) { startActivity(new Intent(UserMenuActivity.this, CreateGroupActivity.class)); } if (pos == 5) { startActivity(new Intent(UserMenuActivity.this, InvitetoCCMActivity.class)); } if (pos == 6) { startActivity(new Intent(UserMenuActivity.this, SearchActivity.class)); } if (pos == 7) { onGroupExpand(2); for (int i = 0; i < groupNames.size(); i++) { mExpandableListView.expandGroup(i); } } /** Click on settings */ if (pos == 8) { startActivity(new Intent(UserMenuActivity.this, SettingsActivity.class)); } if (pos == 10) { System.exit(0); } if (pos == 14) { if (mllpopmenu.getVisibility() == View.VISIBLE) { mllpopmenu.setVisibility(View.INVISIBLE); if (popupWindow.isShowing()) { popupWindow.dismiss(); } } else { mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter( UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data)); } } } } }); } /** Toast message display here.. */ private void showToast(String msg, int time) { Toast.makeText(this, msg, time).show(); } public String showSubscriptionStatus(String friend){ return friend; } } Service.class public class UpdaterService extends Service { private XMPPConnection connection; String Friend; String user = ""; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); super.onCreate(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub showToast("My Service Started", 0); connection = getConnection(); if (connection.isConnected()) { final Roster roster = connection.getRoster(); RosterListener r1 = new RosterListener() { @Override public void presenceChanged(Presence presence) { // TODO Auto-generated method stub XMPPConn.getContactList(); } @Override public void entriesUpdated(Collection<String> arg0) { // TODO Auto-generated method stub //notification("entriesUpdated"); } @Override public void entriesDeleted(Collection<String> arg0) { // TODO Auto-generated method stub //notification("entriesDeleted"); } @Override public void entriesAdded(Collection<String> arg0) { // TODO Auto-generated method stub Iterator<String> it = arg0.iterator(); if (it.hasNext()) { user = it.next(); } RosterEntry entry = roster.getEntry(user); if(entry.getType().toString().equalsIgnoreCase("to")){ int index_of_Alpha = Friend.indexOf("@"); String subID = Friend.substring(0, index_of_Alpha); notification("Hi "+subID+" wants to add you"); } } }; if (roster != null) { roster.setSubscriptionMode(Roster.SubscriptionMode.manual); System.out.println("subscription going on"); roster.addRosterListener(r1); } } else { showToast("Connection lost-", 0); } } protected void showToast(String msg, int time) { Toast.makeText(this, msg, time).show(); } private XMPPConnection getConnection() { return CCMStaticVariable.CommonConnection; } /** Notification manager */ private void notification(CharSequence message) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); int icon = R.drawable.ic_launcher; CharSequence tickerText = message; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Context context = getApplicationContext(); CharSequence contentTitle = "CCM"; CharSequence contentText = message; Intent notificationIntent = new Intent(this, ManageNotification.class); notificationIntent.putExtra("Subscriber_ID",user ); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; final int HELLO_ID = 1; mNotificationManager.notify(HELLO_ID, notification); } } Here is my adapter class public class UserMenuAdapter extends BaseExpandableListAdapter { private ArrayList<String> groups; private ArrayList<ArrayList<ChildItems>> childs; private Context context; public LayoutInflater inflater; ImageView img_availabiliy; private static final int[] EMPTY_STATE_SET = {}; private static final int[] GROUP_EXPANDED_STATE_SET = {android.R.attr.state_expanded}; private static final int[][] GROUP_STATE_SETS = { EMPTY_STATE_SET, // 0 GROUP_EXPANDED_STATE_SET // 1 }; public UserMenuAdapter(Context context, ArrayList<String> groups, ArrayList<ArrayList<ChildItems>> childs) { this.context = context; this.groups = groups; this.childs = childs; inflater = LayoutInflater.from(context); } @Override public Object getChild(int groupPosition, int childPosition) { return childs.get(groupPosition).get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return (long) (groupPosition * 1024 + childPosition); } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { View v = null; if (convertView != null) v = convertView; else v = inflater.inflate(R.layout.child_layout, parent, false); ChildItems ci = (ChildItems) getChild(groupPosition, childPosition); TextView tv = (TextView) v.findViewById(R.id.tvChild); tv.setText(ci.getName()); TextView tv2 = (TextView) v.findViewById(R.id.tvChild2); tv2.setText(ci.getDailyStatus()); img_availabiliy = (ImageView)v.findViewById(R.id.img_childlayout_AVAILABILITY); ImageView friendPics = (ImageView)v.findViewById(R.id.ivFriendPics); if(ci.getStatusState() == 1){ img_availabiliy.setImageResource(R.drawable.online); } else if(ci.getStatusState()==0){ img_availabiliy.setImageResource(R.drawable.offline); } else if (ci.getStatusState()==2) { img_availabiliy.setImageResource(R.drawable.away); } else if(ci.getStatusState()==3){ img_availabiliy.setImageResource(R.drawable.busy); } else{ img_availabiliy.setImageDrawable(null); } if((groupPosition == 1 && childPosition == 0)){ friendPics.setImageResource(R.drawable.inviteto_ccm); img_availabiliy.setVisibility(View.INVISIBLE); } else if(groupPosition == 2 && childPosition == 0){ friendPics.setImageResource(R.drawable.new_ccmgroup); img_availabiliy.setVisibility(View.VISIBLE); }else{ if(ci.getPicture()!= null){ Bitmap bitmap = BitmapFactory.decodeByteArray(ci.getPicture(), 0, ci.getPicture().length); bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, true); friendPics.setImageBitmap(bitmap); }else{ friendPics.setImageResource(R.drawable.avatar); } img_availabiliy.setVisibility(View.VISIBLE); } return v; } @Override public int getChildrenCount(int groupPosition) { return childs.get(groupPosition).size(); } @Override public Object getGroup(int groupPosition) { return groups.get(groupPosition); } @Override public int getGroupCount() { return groups.size(); } @Override public long getGroupId(int groupPosition) { return (long) (groupPosition * 1024); } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { View v = null; if (convertView != null) v = convertView; else v = inflater.inflate(R.layout.group_layout, parent, false); String gt = (String) getGroup(groupPosition); TextView tv2 = (TextView) v.findViewById(R.id.tvGroup); if (gt != null) tv2.setText(gt); /**Set Image on group layout, Max/min*/ View ind = v.findViewById( R.id.explist_indicator); View groupInd = v.findViewById( R.id.llgroup); if( ind != null ) { ImageView indicator = (ImageView)ind; if( getChildrenCount( groupPosition ) == 0 ) { indicator.setVisibility( View.INVISIBLE ); } else { indicator.setVisibility( View.VISIBLE ); int stateSetIndex = ( isExpanded ? 1 : 0) ; Drawable drawable = indicator.getDrawable(); drawable.setState(GROUP_STATE_SETS[stateSetIndex]); } } if( groupInd != null ) { RelativeLayout indicator2 = (RelativeLayout)groupInd; if( getChildrenCount( groupPosition ) == 0 ) { indicator2.setVisibility( View.INVISIBLE ); } else { indicator2.setVisibility( View.VISIBLE ); int stateSetIndex = ( isExpanded ? 1 : 0) ; Drawable drawable2 = indicator2.getBackground(); drawable2.setState(GROUP_STATE_SETS[stateSetIndex]); } } return v; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public void onGroupCollapsed(int groupPosition) { } public void onGroupExpanded(int groupPosition) { } } I just want to update my list in ON PRESENCE CHANGED method in the Service class.. Please suggest me a means to do the same.

    Read the article

  • Android: Unable to access a local website over HTTPS

    - by user1253789
    I am trying to access a locally hosted website and get its HTML source to parse. I have few questions: 1) Can I use "https://An IP ADDRESS HERE" as a valid URL to try and access. I do not want to make changes in the /etc/hosts file so I want to do it this way. 2) I cannot get the html, since it is giving me Handshake exceptions and Certificate issues. I have tried a lot of help available over the web , but am not successful. Here is the code I am using: public class MainActivity extends Activity { private TextView textView; String response = ""; String finalresponse=""; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.TextView01); System.setProperty("javax.net.ssl.trustStore","C:\\User\\*" ); System.setProperty("javax.net.ssl.trustStorePassword", "" ); } private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { } try { URL url = new URL("https://172.27.224.133"); HttpsURLConnection con =(HttpsURLConnection)url.openConnection(); con.setHostnameVerifier(new AllowAllHostnameVerifier()); finalresponse=readStream(con.getInputStream()); } catch (Exception e) { e.printStackTrace(); } return finalresponse; } private String readStream(InputStream in) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = reader.readLine()) != null) { response+=line; } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return response; } @Override protected void onPostExecute(String result) { textView.setText(finalresponse); } } public void readWebpage(View view) { DownloadWebPageTask task = new DownloadWebPageTask(); task.execute(new String[] { "https://172.27.224.133" }); } }

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >