Hot questions for Using Android EditText in listview

Question:

I have a Listview with EditTexts in every cell. Whenever I add text to the point that the EditText grows 1 line, the ListView scrolls to the top (and usually removes the EditText from view by doing so).

I found a few questions about this but they only seem to have "hacks" as answers and nothing that works for me.

ListView scrolls to top when typing in multi-line EditText

Listview with edittext - auto scroll on "next"

EDIT: After a lot of research, I have found that it is because the editText is resizing, causing the ListView layout its subviews and then resetting to the top. I want to find a way for the EditText to grow while staying at the same place.

I tried this because of a suggestion I found online but, even though it keeps the ListView at the right height, it clears the focus from the EditText and I cannot seem to get it back with requestFocus.

private Stirng getTextWatcher(){
return new TextWatcher(){
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
@Override public void afterTextChanged(Editable s) { 
listView.setSelection(index);
  }
 }
}

So what I would need is either:

  1. Have a way for the ListView to not scroll automatically to the top when the subviews are being layed out again or

  2. A way to focus my EditText after having called ListView.setSelected() or 3. Have another way to scroll the ListView that will not clear focus from the EditText.

For option

  1. I have tried scrollTo() and smoothScrollToPosition(). scrollTo for some reason works but hides certain items from the ListView (they become invisible, not loaded). And smoothScrollToPosition() creates an animation where the ListView jumps to the top and then it brings the user back to the Item (and does it 2 or 3 times).

Answer:

As par my view if you want to take input from ListView item by using EditText then you should use TextView in place EdiText and by click of TextView you should open and Input Dialog with EditText that is more simple and good solution. handling of EditText focus in ListView is vary difficult and you need to put extra Listeners for this.

OR

And if you have limited number of input box in your UI/UX then you can implement EditText with CustomListView by using ScrollViews.

Question:

I have 3 activities, A, B and C.The flow of activity is from A to B then C. From C, all the images and value will be returned to B then A. All the returned value and image will be loaded in listView A.

The listView is clickable and once it is clicked, it will intent to B to do some edition. But the problem now is when I edit the text value in B and return to A, I get a new list instead of updating the old one. What's wrong here ? Anyone can help?

Activity C

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_fit_screen);
        selectImage();
        b = (ImageView) findViewById(R.id.imageView3);
        t = (EditText) findViewById(R.id.editText38);
        cancel=(Button)findViewById(R.id.button15);
        ok=(Button)findViewById(R.id.button16);

        cancel.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View arg0) {
                finish();
            }
        });

        ok.setOnClickListener(new View.OnClickListener()
        {  // return to B
            public void onClick(View arg0)
            {
                Intent returnIntent=new Intent();
                text=t.getText().toString();
                b.setDrawingCacheEnabled(true);
                b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
                b.buildDrawingCache(true);
                returnIntent.putExtra("text", text);
                if (b.getDrawingCache() != null) {
                    Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
                    if (bitmap == null) {
                        Log.e("TAG", "getDrawingCache() == null");
                    }
                    Global.img = bitmap;
                }
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });
    }

Activity B

    ImageButton imageButton;
    ImageView viewImage;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.project);
        txt = (EditText) findViewById(R.id.editText36);
        txt1=(TextView)findViewById(R.id.textView57);
        Button b = (Button) findViewById(R.id.button17);
        addListenerOnButton();
        viewImage = (ImageView) findViewById(R.id.imageView2);

        if(getIntent().getExtras()!=null) { //if  has value pass from A
            final String Amount = getIntent().getExtras().getString("result");
            final String description1 = getIntent().getExtras().getString("description");

            txt1.setText(description1);
            txt.setText(Amount);
        }

                b.setOnClickListener(new View.OnClickListener() {  // return to A
                    public void onClick(View arg0) {
                        Intent returnIntent = new Intent();
                        a = "Project";
                        text = txt.getText().toString(); // amount
                        returnIntent.putExtra("text", text);
                        returnIntent.putExtra("a", a);
                        returnIntent.putExtra("c", c);
                        setResult(Activity.RESULT_OK, returnIntent);
                        finish();
                    }
                });
                viewImage.setImageBitmap(Global.img);

                }



    public void addListenerOnButton() {
         imageButton = (ImageButton) findViewById(R.id.imageButton);
         imageButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Global.img=null;
                Intent i = new Intent(B.this,C.class);
                startActivityForResult(i, PROJECT_REQUEST_CODE);
            }

        });

    }

    public void onActivityResult(int requestCode,int resultCode, Intent data)
    {
        if(requestCode==PROJECT_REQUEST_CODE) { // receive fom C
            if(data!=null&&data.hasExtra("text")) {
                c = data.getStringExtra("text");
                txt1.setText(c);
                viewImage.setImageBitmap(Global.img);  // image from C can be shown here
            }


        }
        else if (requestCode==CAMERA_REQUEST_CODE)
        {

        }
    }

}

Activity A

public class Claims1 extends Fragment {

    ListView listV;
    String description;
    String result="";
    String name;
    long as=0;
    TextView c;
    ImageView v;
  ArrayAdapter<String> adapter;
    ArrayList<String> m_listItems = new ArrayList<String>();
    String Text;

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = this.getArguments();
        setHasOptionsMenu(true);
        View claims = inflater.inflate(R.layout.receipt_text, container, false);
        v=(ImageView)claims.findViewById(R.id.imageView4);
        listV = (ListView) claims.findViewById(R.id.listView1);
        android.support.v7.app.ActionBar myActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        myActionBar.setHomeButtonEnabled(true);
        ImageView imageView = new ImageView(myActionBar.getThemedContext());
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        imageView.setImageResource(R.mipmap.create);


        adapter=new ArrayAdapter<String>(getActivity(),R.layout.claims,R.id.textView1,m_listItems);

        android.support.v7.app.ActionBar.LayoutParams layoutParams = new android.support.v7.app.ActionBar.LayoutParams(
                android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT,
                android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
                | Gravity.CENTER_VERTICAL);  // for icon in action bar
        layoutParams.rightMargin = 40;
        imageView.setLayoutParams(layoutParams);
        myActionBar.setCustomView(imageView);

        listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> listView, View view,
                                    int position, long id) {
              if(name.equals("Project")) {
                    Intent intent = new Intent(Claims1.this.getActivity(), B.class);
                    intent.putExtra("bitmap",true);
                    intent.putExtra("name",name);
                    intent.putExtra("result",result);
                    startActivityForResult(intent,0);
                }

            }
        });
        return claims;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.my_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.create1:
                AlertDialogRadio();
                return true;
        }
        return (super.onOptionsItemSelected(item));
    }


    public void AlertDialogRadio() {
        final CharSequence[] ClaimsModel = {"B", "Petrol"};

        AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
        alt_bld.setTitle("Select a Class");
        alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
                .OnClickListener() {

            public void onClick(DialogInterface dialog, int item) {
                if (item == 0) {
                    Intent intent = new Intent(getActivity().getApplicationContext(),B.class);
                    startActivityForResult(intent, 0);
                } else if (item == 1) {
                    Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
                    startActivityForResult(intent, 1);
                } 
                dialog.dismiss();

            }
        });
        AlertDialog alert = alt_bld.create();
        alert.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
                case 0:
                    result = data.getStringExtra("text");
                    name = data.getStringExtra("a");
                    description = data.getStringExtra("c");
                    as = Long.parseLong(result);
                    Log.d("FIRST", "result:"+result);
                    Text="  "+name+"                                  "+"RM"+result+"";
                    m_listItems.add(Text);
                    adapter.notifyDataSetChanged();
                    listV.setAdapter(adapter);

                    break;

                case 1:
                    result = data.getStringExtra("text");
                    name = data.getStringExtra("a");
                    description = data.getStringExtra("c");
                    if (Global.img != null) {
                        v.setImageBitmap(Global.img);
                    }
                    as = Long.parseLong(result);
                    c.setText("                            " + name + "------" + "RM " + result);
                    break;
        }

    }

Edited

Add a global variable in A - private int mClickedPosition; Add mClickedPosition = position; in OnItemClick

then

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    switch (requestCode) {
            case 0:
                result = data.getStringExtra("text");
                name = data.getStringExtra("a");
                description = data.getStringExtra("c");
                as = Long.parseLong(result);
                Log.d("FIRST", "result:"+result);
                Text="  "+name+"                                  "+"RM"+result+"";
                m_listItems.set(mClickedPosition,Text);
                adapter.notifyDataSetChanged();
                listV.setAdapter(adapter);

                break;

11-16 18:15:54.751 23044-23044/com.example.project.project E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.project.project, PID: 23044 java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=0, result=-1, data=Intent { (has extras) }} to activity {com.example.project.project/com.example.project.project.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at android.app.ActivityThread.deliverResults(ActivityThread.java:3681) at android.app.ActivityThread.handleSendResult(ActivityThread.java:3724)

 m_listItems.set(mClickedPosition,Text);

Answer:

in your activity A onActivityResult method when you return from activity B after editing you are adding new item into arraylist using this code m_listItems.add(Text);

instead of adding new item you update the array list using this code

m_listItems.set(position Text);

Question:

I try to scroll listview to the very bottom and it works this way:

listview.setSelection(listview.getCount()-1);

(shame on you Google, basic thing scrollToBottom method, and we had to find other way to achieve it..)

But this doesn't work.. when before using it you type some text.. into EditText View. Funny? Not at all.

Add element to listview -> scrollToBottom -> you are at the very bottom - works
Add element to listview -> type something in EditView -> scrollToBottom - not works
Add element to listview -> type something in EditView -> click anywhere in screen -> scrollToBottom - works!

As we can see problem is strange and weird, I was trying to [anyView].performClick(); but no luck..

Any idea why typing in EditText makes me thinking about Android Dev Team responsible for listview is so lame? And how we can find workaround for this bug.

Thanks for help! :)

Some code:

<ListView
     android:id="@+id/nativeLog"
     android:focusable="false"
     android:focusableInTouchMode="false"
     android:transcriptMode="normal"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:paddingTop="0dp"
     android:paddingBottom="10dp"
     android:clipToPadding="false"
     android:paddingLeft="0dp"
     android:paddingRight="0dp"
     android:cacheColorHint="#00000000"
     android:background="@drawable/gray_bg"
     android:listSelector="@color/transparent"
     android:divider="@null"
     android:dividerHeight="0dp"/>

[...]

<EditText
     android:id="@+id/boxInterfaceEditbox"
     android:scrollHorizontally="false"
     android:inputType="textCapSentences|textLongMessage|textMultiLine|textNoSuggestions"
     android:singleLine="false"
     android:imeOptions="actionSend"
     android:layout_width ="0dp"
     android:layout_weight="1"
     android:layout_height ="wrap_content"
     android:layout_marginLeft="5.5dp"
     android:layout_marginRight="5.5dp"
     android:paddingTop="8.2dp"
     android:paddingBottom="8.2dp"
     android:paddingLeft="8dp"
     android:paddingRight="8dp"
     android:minHeight="@dimen/nav_interface_btn_size"
     android:maxHeight="90dp"
     android:textColor="#bbb"
     android:textSize="15.25dp"
     android:gravity="top"
     android:background="@drawable/nav_boxtextarea"/>

And java

scrollToBottomRunnable = new Runnable() {
     @Override
     public void run() {
         log.setSelection(log.getCount() -1);
     }
};

Answer:

As we tried everything in comments at least we found that should call notifyDatasetChanged() after adding items to list view and after when you switch visibility of listview-footer-child too.

Question:

I am having trouble accessing my UIs from MainActivity after creating the Intent methods.My app crashes when I select the SelectPLayer and SelectPLayer2 activities from my MainActivity. I am also having trouble getting the Clickable ListViews to go to the specified TextView in GameEmulator.

//MainActivity.java


        //Class to select player 1
        public class SelectPlayer extends Activity {


            //Public static array list with adapter to crete the array and reference for listview being sent by intent from AddPLayer class
            public static ArrayList<String> list = new ArrayList<>();
            public static ArrayAdapter<String> adapter;
            ListView selectView;
            TextView title;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.selectplayer);

                //Identify selectview ListView
                selectView = findViewById(R.id.selectview) ;
                selectView.setClickable(true);
                selectView.setVisibility(View.VISIBLE);

                //Using adapter for ListView menu
                adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
                selectView.setAdapter(adapter);
                selectView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String item =(String) parent.getItemAtPosition(position); // finding the item which has been clicked by the user
                        Intent intent = new Intent(SelectPlayer.this, GameEmulator.class); //starting an intent to call GameEmulator Activity
                        intent.putExtra(GameEmulator.value, item);// Putting the value clicked by user in intent
                        startActivity(intent); // starting GameEmulator Activity
                    }
                });
                //Using intent to retrieve string from AddPlayer Activity
                    Intent i = getIntent();
                    String data = i.getExtras().getString("text_key");
                    list.add(data);
                    changeList();
            }
            public static void changeList()
            {

                adapter.notifyDataSetChanged();
            }
        }

//Addplayer.java

import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.os.Bundle;
import android.widget.Button;
import android.content.Intent;

//Addplayer class to add players using intent to separate activities
public class AddPlayer extends Activity{

    //Declare buttons and edittext
    Button listButtonplayer1;
    Button listButtonplayer2;
    EditText playerIn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playerinput);


        //Identify buttons and editext
        playerIn = (EditText) findViewById(R.id.inputname);

        listButtonplayer1 = (Button)findViewById(R.id.addbutton);
        listButtonplayer1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Using intent to send input to SelectPLayer Class
                Intent i = new Intent(AddPlayer.this,SelectPlayer.class);

                //Using string text_key to get and send string through intent
                i.putExtra("text_key", playerIn.getText().toString());


                //Start intent activity
                startActivity(i);
            }
        });

        //Second button I am trying to use for SelectPLayer2 activity only.
        listButtonplayer2 = (Button)findViewById(R.id.addbutton2);
        listButtonplayer2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Using intent to send input to SelectPLayer2 Class
                Intent in = new Intent(AddPlayer.this, SelectPlayer2.class);

                in.putExtra("text_key", playerIn.getText().toString());

                startActivity(in);
            }
        });
    }
}
Selectplayer1.java
//Class to select player 1
public class SelectPlayer extends Activity {


    //Public static array list with adapter to crete the array and reference for listview being sent by intent from AddPLayer class
    public static ArrayList<String> list = new ArrayList<>();
    public static ArrayAdapter<String> adapter;
    ListView selectView;
    TextView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selectplayer);

        //Identify selectview ListView
        selectView = findViewById(R.id.selectview) ;
        selectView.setClickable(true);
        selectView.setVisibility(View.VISIBLE);

        //Using adapter for ListView menu
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
        selectView.setAdapter(adapter);
        selectView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String item =(String) parent.getItemAtPosition(position); // finding the item which has been clicked by the user
                Intent intent = new Intent(SelectPlayer.this, GameEmulator.class); //starting an intent to call GameEmulator Activity
                intent.putExtra(GameEmulator.value, item);// Putting the value clicked by user in intent
                startActivity(intent); // starting GameEmulator Activity
            }
        });
        //Using intent to retrieve string from AddPlayer Activity
            Intent i = getIntent();
            String data = i.getExtras().getString("text_key");
            list.add(data);
            changeList();
    }
    public static void changeList()
    {

        adapter.notifyDataSetChanged();
    }
}
//Selectplayer2.java

//Class to select player 2
public class SelectPlayer2 extends Activity {

    //Public static array list with adapter to crete the array and reference for listview being sent by intent from AddPLayer class
    public static ArrayList<String> list1 = new ArrayList<>();
    public static ArrayAdapter<String> adapter1;

    ListView selectView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selectplayer2);

        selectView2 = (ListView) findViewById(R.id.selectview1);
        selectView2.setClickable(true);
        selectView2.setVisibility(View.VISIBLE);

        //Using adapter for ListView menu
        adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list1);
        selectView2.setAdapter(adapter1);
        selectView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    String item =(String) parent.getItemAtPosition(position); // finding the item which has been clicked by the user
                    Intent in = new Intent(SelectPlayer2.this, GameEmulator.class); //starting an intent to call GameEmulator Activity
                    in.putExtra(GameEmulator.value, item);// Putting the value clicked by user in intent
                    startActivity(in); // starting GameEmulator Activity
            }
        });

        //Using intent to retrieve string from AddPlayer Activity
        Intent in = getIntent();
        String data = in.getExtras().getString("text_key");
        list1.add(data);
        changeList();
    }
    public static void changeList()
    {

        adapter1.notifyDataSetChanged();
    }
}

I have seperate static array lists, but the listview clickables are still showing on both textviews in the GameEmulator class. Here is my error log trying to click the button for SelectPLayer UI:

07-17 23:41:37.296 13468-13468/com.example.ryan_.ryansplayersapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ryan_.ryansplayersapp, PID: 13468
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ryan_.ryansplayersapp/com.example.ryan_.ryansplayersapp.SelectPlayer}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
        at com.example.ryan_.ryansplayersapp.SelectPlayer.onCreate(SelectPlayer.java:47)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

Answer:

 String data = i.getExtras().getString("text_key");

Your getExtras() is returning null. Make sure you initialise your intent properly.

Question:

I'm building a very simple list app on android where I have an edittext for input, a listview to store saved input, and a button to push text from the edittext to listview. Right now I am trying to handle the error key, so not only does it not create a new line on press, but also so that it will send the text to the listview when I click the enter button.

I set the edittext to singleline to prevent new lines, and I added an onEditorActionListener to my edittext to handle the keyevents. Here's my code.

activity_main.xml

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myEditText"
    android:imeOptions="actionSearch|actionGo"
    android:hint="Enter a new item"
    android:singleLine="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_toLeftOf="@+id/myImageButton"
    android:layout_toStartOf="@+id/myImageButton"/>

MainActivity.java

public class MainActivity extends AppCompatActivity {
// Declare our View variables
private ListView mListView;
private EditText mEditText;
private Button mDoneButton;
private ImageButton mImageButton;
private static final String TAG = MainActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Assign the view from the layout file to the corresponding variables
    mListView = (ListView) findViewById(R.id.myListView);
    mEditText = (EditText) findViewById(R.id.myEditText);
    mDoneButton = (Button) findViewById(R.id.myDoneButton);
    mImageButton = (ImageButton) findViewById(R.id.myImageButton);


    // Listview items adapter
    items = new ArrayList<>();
    readItems();
    itemsAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, items);
    mListView.setAdapter(itemsAdapter);

    //setup enter listener
    mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //handle search key click
                onAddItem(v);
                Log.d(TAG, "Handled!");
                return true;
            }
            if (actionId == EditorInfo.IME_ACTION_GO) {
                //Handle go key click
                onAddItem(v);
                return true;
            }
            return handled;
        }
    });
}

//Add item to list from either the button or enter
public void onAddItem(View v) {
    String itemText = mEditText.getText().toString();
    itemsAdapter.add(itemText);
    mEditText.setText("");

    writeItems();
}

The code giving me trouble. I'm not even getting anything back from that log.d, but everything else in the code, except for this listener, works as expected.

        //setup enter listener
    mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //handle search key click
                onAddItem(v);
                Log.d(TAG, "Handled!");
                return true;
            }
            if (actionId == EditorInfo.IME_ACTION_GO) {
                //Handle go key click
                onAddItem(v);
                return true;
            }
            return handled;
        }
    });

Answer:

In order to use IME_ACTION_SEARCH and others you need to specify these actions in your xml-layout as well:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myEditText"
    android:imeOptions="actionSearch|others"
    ...
    />

Question:

I have a DialogFragment in which there is ListView, each ListItem has three TextViews and one EdiText, EditText allows integer values which can be changed as per the user requirement. So onClick of positive button of dialog I want to send thoes updated Integer value to the server. While fetching EditText's text it fetches the old values not the updated one.

The code I have written

 View v;

    ArrayList<String> edValues = new ArrayList<String>();

    EditText et;

                            for (int i = 0; i < alObj.size(); i++) {
                                v = adapter.getView(i, null, null);
                                et = (EditText) v.findViewById(R.id.user_bill_edit);

//Dialog

public class CaseUserList extends DialogFragment  {


    private Context context;
    private String pipeSeparatedUserLists;
    Boolean isOperationEdit = false;
    String strCaseId = null;
    private UserBillRateAdapter adapter;
    ArrayList<Object> alObj;

    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        context = getActivity();
        strCaseId = getArguments().getString(CaseConstants.TABLE_CASE_LIST_CASE_ID);
        //isOperationEdit = getArguments().getBoolean("isEdit");

        //Send network request to get the list
        new userBillRateList().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        //Prepare the list layout
        View view = getActivity().getLayoutInflater().inflate(R.layout.layout_case_user_list, null);
        builder .setView(view)
                .setPositiveButton("Update", new Dialog.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        View v;
                        ArrayList<String> edValues = new ArrayList<String>();
                        EditText et;

                        for (int i = 0; i < alObj.size(); i++) {
                            v = adapter.getView(i, null, null);
                            et = (EditText) v.findViewById(R.id.user_bill_edit);
                            edValues.add(et.getText().toString());
                        }
                    }
                })

                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        CaseUserList.this.getDialog().cancel();
                    }
                });
        return builder.create();
    }

    /**
     * Async task to fetch list of all possible Witness
     */
    private class userBillRateList extends AsyncTask<Void, Void, ArrayList<Object>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected ArrayList<Object> doInBackground(Void... voids) {
            Network billRateList = new Network(getActivity(),CaseConstants.SERVICE_CASE_USER_BILL_RATE
                    + Constants.CONSTANT_CONTACT_ID + ","
                    + strCaseId);

            return HelperFunctions.convertJsonToDataModel(billRateList.getJsa_Output(),
                    UserBillingRateModel.class);
        }

        @Override
        protected void onPostExecute(final ArrayList<Object> arrayList) {
            super.onPostExecute(arrayList);
            alObj = arrayList;
            ListView allListsView = (ListView) getDialog().findViewById(R.id.list_view_case_user_list);

            if(arrayList.isEmpty()) {
                ((TextView) getDialog().findViewById(R.id.user_list_empty_text_view)).setVisibility(View.VISIBLE);
            } else {
                ((EditText)getDialog().findViewById(R.id.user_list_search)).setVisibility(View.VISIBLE);
                adapter = new UserBillRateAdapter(getActivity(),arrayList);

                allListsView.setAdapter(adapter);
                allListsView.setTextFilterEnabled(true);
            }
            getDialog().show();
        }
    }
}
                                    edValues.add(et.getText().toString());
                                }

//Adapter

public class UserBillRateAdapter extends BaseAdapter {
    /**
     *  The following variable contains the File list in the CloudFileList bean format.
     */
    private ArrayList<Object> al_List;
    /**
     * The context of the activity being worked on
     */
    private Context context;
    ViewHolder viewContainer = null;
    ArrayList<Object> alDataObj;

    public UserBillRateAdapter(Context context, ArrayList<Object> al_List){
        this.al_List = al_List;
        this.context = context;
        alDataObj = new ArrayList<>();
    }

    @Override
    public int getCount() {
        if(al_List != null)
            return al_List.size();
        return 0;
    }

    @Override
    public Object getItem(int position) {
        return al_List.get(position);
    }

    @Override
    public long getItemId(int position) {
        return Long.valueOf(((UserBillingRateModel) al_List.get(position)).ContactId);
    }

    @Override
    public View getView(int position,View viewConvert, ViewGroup parent) {
        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        viewContainer = null;
        if(viewConvert == null) {
            viewConvert = mInflater.inflate(R.layout.layout_user_bill_list, null);
            viewContainer = new ViewHolder();
            viewContainer.txtUserName = (TextView) viewConvert.findViewById(R.id.user_name_txt);
            viewContainer.txtUserRole = (TextView) viewConvert.findViewById(R.id.user_role);
            viewContainer.txtUserRate = (TextView) viewConvert.findViewById(R.id.user_bill_txt);
            viewContainer.edUserRate = (EditText) viewConvert.findViewById(R.id.user_bill_edit);
            viewConvert.setTag(viewContainer);
        } else
            viewContainer = (ViewHolder) viewConvert.getTag();

        final UserBillingRateModel beanListItem = (UserBillingRateModel) al_List.get(position);
        viewContainer.txtUserName.setText(beanListItem.FullName);
        viewContainer.txtUserRate.setText(beanListItem.BillingRate);
        viewContainer.txtUserRole.setText(beanListItem.RoleName);
        viewContainer.edUserRate.setText(beanListItem.BillingRate);
        return viewConvert;
    }

    public class ViewHolder{
        TextView txtUserName;
        TextView txtUserRole;
        TextView txtUserRate;
        EditText edUserRate;
    }
}

Answer:

Try to replace adapter.getView(i) with yourListView.getChildAt(i). I suppose it will help.

Question:

I have a listView in Activity A , which the value are returned from Activity B.When the list is clicked, it will intent to Activity B for edit.

Activity B

 @Override
 protected void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.add_details_information);
         addItemsOnSpinner();
         if(getIntent().getExtras()!=null)  // if has value pass from A
          {
              final String Project1=getIntent().getStringExtra("ReceiveProject");
              final String Description1=getIntent().getStringExtra("ReceiveDescription");
              final String Progress1=getIntent().getStringExtra("ReceiveProgress");
              final String TimeIn1=getIntent().getStringExtra("ReceiveTimeIn");
              final String TimeOut1=getIntent().getStringExtra("ReceiveTimeOut");
              //project.setText(Project1);
              description.setText(Description1);
              //progressText.setText("Covered:")
              timeIn.setText(TimeIn1);
              timeOut.setText(TimeOut1);
              }

            save.setOnClickListener(new View.OnClickListener()
             {  // return to A

           @Override
          public void onClick(View v)
          {
            Intent returnIntent=new Intent();
            Project=project.getSelectedItem().toString(); // Spinner Value
            Description=description.getText().toString(); //from editText
            progress=seekBar.getProgress(); // From SeekBar
            returnIntent.putExtra("Project",Project);
            returnIntent.putExtra("Description", Description);
            returnIntent.putExtra("progress", progress);
            Toast.makeText(getApplicationContext(), progress+"", Toast.LENGTH_LONG).show();
            returnIntent.putExtra("TimeIn", TimeIn);
            returnIntent.putExtra("TimeOut",TimeOut);
            setResult(Activity.RESULT_OK,returnIntent);
            finish();
            }
           });

 public void  addItemsOnSpinner()
    {
        project=(Spinner)findViewById(R.id.SpinnerProject);
        List<String> list = new ArrayList<String>();
        list.add("TRN-XXX-XXX");
        list.add("Pro-XXX-XXX);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.spinner_item, list);
        //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        project.setAdapter(adapter);
    }

Activity A

   listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                mClickedPosition = position;
                Intent i = new Intent(getApplication(), Add_Details_Information.class);
                i.putExtra("ReceiveProject", ReceiveProject);
                i.putExtra("ReceiveDescription", ReceiveDescription);
                i.putExtra("ReceiveProgress", ReceiveProgress);
                i.putExtra("ReceiveTimeIn", ReceiveTimeIn);
                i.putExtra("ReceiveTimeOut", ReceiveTimeOut);
                startActivityForResult(i,PROJECT_REQUEST_CODE);
            }
        });
    }

I know that we can use setText to display the passed value from A to B for editText, but how about the spinner and seekBar value ?

This is the listView in Activity A. Value are returned from Activity B.

When listView is clicked, it will goes to B again to edit.

So how can I make the spinner in B display Pro-XXX-XXX and the seekBar goes to 48 ? Any idea or suggestion ? Thanks a lot

Edited

After used the answer from @Clairvoyant, now I get this (for spinner value).

Activity A

There are 4 list in Activity A.

Assume first list is clicked.

Everything works fine just the spinner(Project/Service/Training) display wrong value. It display the spinner value from last list(PRO-SKM-D5) instead of itself(Pro-XXX-XXX)


Answer:

First Step: Make your addItemsOnSpinner like as below:

    public void addItemsOnSpinner(String value) 
    { 
     int position = 0; 
     project=(Spinner)findViewById(R.id.SpinnerProject); 
     List<String> list = new ArrayList<String>(); 

     list.add(position,"TRN-XXX-XXX"); 
     list.add("Pro-XXX-XXX"); 

     for(int i=0; i<list.size() ; i++){
         if(list.get(i).equalsIgnoreCase(value)){
             position = i;
             break;
         }
     }


    ArrayAdapter<String> adapter = new ArrayAdapter<String>      (getApplicationContext(),R.layout.spinner_item, list); 
     //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    project.setAdapter(adapter); 

    project.setSelection(position); 
   }

Second Step: call the above method when you are assigning value to the variable you have to show in spinner here for eg: project1 is the string value which you want to show in spinner then call the method as follows:

final String Project1=getIntent().getStringExtra("ReceiveProject");
 addItemsOnSpinner(Project1);

Question:

greetings my fellow developer i am working on a project in which i have to deal with the contacts list, i have created a contact list view and an EditText for searching purpose, my ListView is working as i expect it to, except searching, here is my listview

<LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">

        <EditText
            android:id="@+id/contacts_search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:drawableEnd="@drawable/ic_search"
            android:drawableRight="@drawable/ic_search"
            android:hint="@string/contacts_search"
            android:maxLines="1" />

        <ListView
            android:id="@+id/contactsListView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:divider="@color/colorAccent"
            android:dividerHeight="1dp"
            android:footerDividersEnabled="false" />
    </LinearLayout>

and this is my listviewitem

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:descendantFocusability="blocksDescendants"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/contact_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/contacts_image"
        android:layout_gravity="center" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/list_view_margin_vertical"
        android:layout_marginTop="@dimen/list_view_margin_vertical"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/contact_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
            android:textColor="@color/colorBlack" />

        <TextView
            android:id="@+id/contact_number"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="@color/colorGrey" />
    </LinearLayout>

    <CheckBox
        android:id="@+id/contact_check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:clickable="false" />
</LinearLayout>

and i am using

SEARCH.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            contactAdapter.getFilter().filter(s); // not working,throwing exception when i do CONTACTS.get(position); in adapter getview()
        }
    });

and in my adapter class i have getfilter function, which is not working

@NonNull
@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<Contact> filtered = new ArrayList<>();
            for(Contact contact:ORIGNAL){
                if(contact.getName().toLowerCase().contains(constraint)){
                    filtered.add(contact);
                }
            }
            FilterResults results = new FilterResults();
            results.count = filtered.size();
            results.values = filtered;
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if(constraint.length() > 0 ) {
                CONTACTS = (ArrayList<Contact>) results.values;
                notifyDataSetChanged();
            }
        }
    };
}

but i cant get the results of search view, it crashes with index out of bound exception where in getView() of adapter class where i am trying CONTACTS.get(position), any help is appritiated


Answer:

greetings my fellow developers, so i think i have found a solution to my problem, i think that this is the optimal solution too, i have made some changes to getFilter function in my adapter class

@NonNull
@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (constraint.length() == 0) {
                results.count = ORIGNAL.size();
                results.values = ORIGNAL;
            } else if (constraint.length() > 0) {
                List<Contact> filtered = new ArrayList<>();
                for (Contact contact : ORIGNAL) {
                    if (contact.getName().toLowerCase().contains(constraint)) {
                        filtered.add(contact);
                    }
                }
                results.count = filtered.size();
                results.values = filtered;
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (constraint.length() == 0) {
                CONTACTS.clear();
                CONTACTS.addAll(ORIGNAL);
            } else if (constraint.length() > 0) {
                CONTACTS.clear();
                CONTACTS.addAll((ArrayList<Contact>) results.values);
            }
            notifyDataSetChanged();
        }
    };
}

and one other thing i figured out that id i assign my orignal arraylist with simple assignment operator "=" it passes address of the contact array, i have used these lines to assign my orignal array in my adapter constructor

this.ORIGNAL = new ArrayList<>();
this.ORIGNAL.addAll(contacts);

i think this is the only easy and fastest way to search through custom listview, but if anyone of you guys think that there is a better way, please share below.

Question:

I have a litview in my code and into each item there is an edittext with a button , So what i want to do is get the edittext's value when press on the button of an listview's item.

I'v tried to get the value by declaring it like this , but it returns null value !

public View getView(int i, View view, ViewGroup viewGroup){
LayoutInflater linflater = getLayoutInflater();
View view1 = linflater.inflate(R.layout.row_view, null);
final EditText replyfld = (EditText) view1.findViewById(R.id.replyfld);
final Button sendreplybtn = (Button)view1.findViewById(R.id.sendreplybtn);

sendreplybtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String thereplyvalue = replyfld.getText().toString();
Toast.makeText(MessagesActivity.this, thereplyvalue, Toast.LENGTH_SHORT).show();
}
});
}

What to do please ?


Answer:

From the code at pastebin.com/HejVn4bb .

Looks like calling replytogglebtn.setFavorite(false,true); (Line:101) in onClickListener before getting text is the problem because setOnFavoriteChangeListener() clears the edittext.

just get text before the setFavorite(false,true);