close custom Dialog android - android

I created a custom dialog with spinner and OK button. I have populated this spinner with some items and inflated the layout.If I click OK button dialog will dismiss.
I set the spinner
spinner.performCLick();
is there is any way to get spinner selected item and to close the dialog without pressing OK button. I have tried
button.performclick();
but no use.

see my below code it may help you.
package com.Test_dia;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class Test_diaActivity extends Activity {
private Button btn;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showalert();
}
});
}
protected void showalert() {
// TODO Auto-generated method stub
final Dialog dia = new Dialog(this);
dia.setContentView(R.layout.dia);
final String a[] = { "select one", "android", "java", "php" };
Button btnok = (Button) dia.findViewById(R.id.button2);
Spinner spin = (Spinner) dia.findViewById(R.id.spinner1);
btnok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dia.dismiss();
}
});
spin.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, a));
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if (arg2 > 0) {
Toast.makeText(Test_diaActivity.this,
"You Selected :" + a[arg2], Toast.LENGTH_SHORT)
.show();
dia.dismiss();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
dia.show();
}
}
main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click here" />
</LinearLayout>
dia.xml
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="16dp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/spinner1"
android:text="ok" />
This code is work for me perfectly ok.
enjoy....

EDIT (removed previous non-suitable answer)
I'm going to assume that your issue is that using setOnItemSelectedListener is firing 'onItemSelected' on startup (thus selecting the first item in the spinner without any user input) and you don't want that.
If that is the case, try the following.
Set a class variable:
private int newSpinner = 0;
Then in the setOnItemSelectedListener:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,int pos, long id) {
if (newSpinner != 0) {
// Do your code thing here
dismiss();
} else {
newSpinner++
}
}
});

Related

Issue while using contextmenu with listview items in a popupwindow

I am developing an android application, my proposal is have two clickable textviews on the page and when user press each of the textview, a listview in a popupwindow will shows under the textview, when user choose a listview item, the textview will be setText() as the name as user selected, when user perform long click on the textview or on the listview item, a contextmenu can be shown to allow user "edit"(jump to a new activity for that) or "delete" the selected item and after that the list adapter can update the list accordingly.
I have finished the code of registerContextMenu for the textview and it works, but the context menu won't show after I added the same code to the listview, I also tried add OnCreateContextMenuListener to the listview but failed again. can any expert help to look into this? thanks a lot.
here is the code:
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
/**
* #author Allen
*
*
*/
public class ProfileActivity extends Activity {
private TextView aTextView;
private TextView bTextView;
private View popupWindow;
// to initial popupwindow width and height
private final int popupWindowWidth = 400;
private final int popupWindowHeight = 350;
// the background drawable for popupWindow
ColorDrawable blackBackground = new ColorDrawable(Color.BLACK);
private PopupWindow aPW;
private ListView aListView;
private ArrayAdapter<String> aListViewAdapter;
private List<String> popupNameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_page);
init();
Toast.makeText(this, "Long press item to modify", Toast.LENGTH_SHORT).show();
}
private void init() {
aTextView = (TextView) findViewById(R.id.aSelectionTextView);
aTextView.setText("Pls select");
aTextView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
//to bTextView will be the same process, only the popupnamelist //will be the different list
popupNameList = new ArrayList<String>();
popupWindow = this.getLayoutInflater().inflate(R.layout.profile_popup_window, null);
aPW = new PopupWindow(popupWindow, popupWindowWidth, popupWindowHeight);
addOnClickListeners();
}
private void aSelection() {
// TODO Auto-generated method stub
popupNameList = new ArrayList<String>();
popupNameList.add("abc");
popupNameList.add("ABC");
popupNameList.add("123");
// to enable the outside click dismiss the PW
aPW.setBackgroundDrawable(blackBackground);
aPW.setOutsideTouchable(true);
// to limit dispatching the click event.
aPW.setFocusable(true);
aListView = (ListView) popupWindow.findViewById(R.id.profile_popup_lstview);
aListViewAdapter = new ArrayAdapter<String>(this, R.layout.profile_listview_item, popupNameList);
aListView.setAdapter(aListViewAdapter);
aListView.setLongClickable(true);
this.registerForContextMenu(aListView);
aListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
aTextView.setText(popupNameList.get(position));
aPW.dismiss();
}
});
aListView.setOnCreateContextMenuListener(mListOnCreateContextMenuListener);
}
private void addOnClickListeners() {
// TODO Auto-generated method stub
aTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
aSelection();
aPW.showAsDropDown(findViewById(R.id.aSelectionTextView), 0, -10, Gravity.START);
}
});
this.registerForContextMenu(aTextView);
}
public void onLaunchDoneClick(View view) {
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
// menu.setHeaderTitle("Operation");
menu.add(0, 0, 0, getString(R.string.edit));
menu.add(0, 1, 0, getString(R.string.delete));
}
private final OnCreateContextMenuListener mListOnCreateContextMenuListener = new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
Toast.makeText(getApplicationContext(), "onCreateContextMenu()", 1000).show();
menu.add(0, 0, 0, getString(R.string.edit));
menu.add(0, 1, 0, getString(R.string.delete));
}
};
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case 0:
Toast.makeText(getApplicationContext(), popupNameList.get(menuInfo.position), 1000).show();
aListViewAdapter.notifyDataSetChanged();
break;
case 1:
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}
The layout xml is here:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/bSelectionTextView"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignEnd="#+id/aSelectionTextView"
android:layout_alignStart="#+id/aSelectionTextView"
android:layout_toRightOf="#+id/textView2"
android:layout_below="#+id/aSelectionTextView"
android:gravity="start|center"
android:text="BSelectionTextView"
android:textSize="20sp" />
<Button
android:id="#+id/okButton"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#id/dSelectionTextView"
android:layout_centerHorizontal="true"
android:background="#drawable/my_button_style"
android:gravity="center"
android:onClick="onLaunchDoneClick"
android:text="#string/Done"
android:textSize="18sp"
android:visibility="gone" />
<TextView
android:id="#+id/textView1"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_alignParentTop="true"
android:gravity="start|center"
android:text="ASelection"
android:textSize="18sp" />
<TextView
android:id="#+id/textView2"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_below="#id/textView1"
android:gravity="start|center"
android:text="BSelection"
android:textSize="18sp" />
<TextView
android:id="#+id/aSelectionTextView"
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/textView1"
android:clickable="true"
android:gravity="start|center"
android:text="ASelectionTextView"
android:textSize="20sp" />
</RelativeLayout>

Unfortunately App has stopped - error in Spinner

I have tried everything but still am not able to figure out what is wrong in this code, whenever I click on the Button 'Get Fare' , a dialog opens showing "Unfortunately app has stopped". Please help ...
Code for MetroFare.java
package com.myapp.anuj;
import com.myapp.anuj.MetroFare;
import com.myapp.anuj.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class MetroFare extends Activity implements OnClickListener, OnItemSelectedListener{
String start[] = {"Shastri Nagar", "Kashmere Gate", "Dwarka Mor"};
String dest[] = {"Pratap Nagar", "Rajiv Chowk", "Kirti Nagar"};
Spinner starting, destination;
Button getfare;
int fare = 0;
int s=0, d=0;
TextView result;
int farearray[][] = {{8,15,14}, {10,12,15}, {21,18,15}};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.kuchbhi);
getfare = (Button) findViewById(R.id.bGetFare);
result = (TextView) findViewById(R.id.tvShowFare);
getfare.setOnClickListener(this);
ArrayAdapter<String> adapterStart = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, start);
ArrayAdapter<String> adapterDest = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, dest);
starting = (Spinner) findViewById(R.id.spinnerStart);
destination = (Spinner) findViewById(R.id.spinnerDest);
starting.setAdapter(adapterStart);
destination.setAdapter(adapterDest);
starting.setOnItemSelectedListener(this);
destination.setOnItemSelectedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String sfare = getString(fare);
result.setText(sfare);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
s = starting.getSelectedItemPosition();
d = destination.getSelectedItemPosition();
fare = farearray[s][d];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Code for kuchbhi.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinnerStart"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/spinnerDest"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/bGetFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Fare" />
<TextView
android:id="#+id/tvShowFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
As I mentioned, your problem is this call: getString(fare), which is attempting to retrieve a String resource with an id the value of fare. Judging from your code, I'm assuming that you're simply trying to display the String value of fare in a TextView, in which case change that call as follows:
String sfare = String.valueOf(fare);

SeekBar in a DialogFragment

I am trying to read stuff from a SeekBar in Android that's within a DialogFragment. It keep crashing. The SeekBar alone comes up no problem, but whenever I try to override functions so I can use the SeekBar for something it keeps crashing. I've tried copying basically what I've seen other people post as working code (though not within a DialogFragment) but it doesn't work. Can someone tell me what's wrong here?
numColumnsControl = (SeekBar) getActivity().findViewById(R.id.seekBar1);
numColumnsControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
//#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean fromTouch)
{
((TextView) (getActivity().findViewById(R.id.textView2))).setText(String.valueOf(progress));
}
//#Override
public void onStartTrackingTouch(SeekBar arg0)
{
// TODO Auto-generated method stub
}
//#Override
public void onStopTrackingTouch(SeekBar arg0)
{
// TODO Auto-generated method stub
}
});`
It keeps crashing whenever I perform the action to open the DialogFragment. When I comment out the entire section it is fine. The problem is somehow overriding those functions, even when they're empty. When this entire section is commented the View comes up with SeekBars and TextViews.
I don't think this is important but here's the XML for the DialogFragment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/titleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Settings"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/seekBar1"
android:layout_marginTop="20dp"
android:text="NumShifts"
android:textAppearance="?android:attr/textAppearanceSmall" />
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:gravity="center"
android:layout_gravity="center"
android:max="15"
android:progress="6"
android:secondaryProgress="0"/>
<SeekBar
android:id="#+id/SeekBar01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView3"
android:gravity="center"
android:layout_gravity="center"
android:max="9"
android:progress="3"
android:secondaryProgress="0"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/titleText"
android:layout_below="#+id/titleText"
android:layout_marginTop="18dp"
android:text="NumColumns"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</LinearLayout>
Here is the whole code from the class:
package com.example.[I have to hide this name];
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SettingsDialogueFragment extends DialogFragment
{
private int numColums;
private int numShifts;
private Context ctx;
private SeekBar numColumnsControl = null;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
ctx = getActivity();
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater= getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.settings_menu, null))
.setPositiveButton("DONE", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
//done
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
LinearLayout settings = new LinearLayout(ctx);
numColumnsControl = (SeekBar) getActivity().findViewById(R.id.seekBar1);
Activity myActivity = getActivity();
if(myActivity == null)
{
Log.e("bill", "bill");
}
if(numColumnsControl == null)
{
Log.e("smith", "smith");
}
numColumnsControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
//#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean fromTouch)
{
((TextView) (getActivity().findViewById(R.id.textView2))).setText(String.valueOf(progress));
Log.e("asd", "asd");
}
//#Override
public void onStartTrackingTouch(SeekBar arg0)
{
Log.e("asdf", "asdf");
// TODO Auto-generated method stub
}
//#Override
public void onStopTrackingTouch(SeekBar arg0)
{
Log.e("asdfg", "asdfg");
// TODO Auto-generated method stub
}
});
return builder.create();
}
}
Based on your comment
'The error is a NullPointerException, which occurs on line 51 which is
the 2nd line in the fragment I gave you
("numColumnsControl.setOnSeekBarChangeListener(new
OnSeekBarChangeListener() ")'
Check if findViewById(R.id.Seekbar1) doesn't returns null. If it does, Make sure your dialog layout is inflated before requesting any view elements from the layout.
It is also possible something is going wrong with the R references (try project -> clean in eclipse) .
Edit I'm not sure if it works, but try to overide onViewCreated() and place your findViewById and setOnSeekBarChangeListener code here.
Edit in some way onViewCreated() is not called (Android DialogFragment onViewCreated not called). This makes the solution a little more difficult. You need to inflate the view first and perform an findViewById on the inflated view.
View menuView = inflater.inflate(R.layout.settings_menu);
numColumnsControl = (SeekBar) menuView.findViewById(R.id.seekBar1, null);
numColumnsControl.setOnSeekBarChangeListener ...
builder.setView(menuView);

Adding ListView item from another Layout

In my app there is two layout first.xml and activity_main.xml. In first Layout there is a button and ListView (Code):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<ListView
android:id="#+id/listView_items"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
And this Layout is connected with MainActivty:
package com.example.listview2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView lvItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button but = (Button) findViewById(R.id.but);
lvItem = (ListView)this.findViewById(R.id.listView_items);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListActivity.class);
startActivity(intent);
}
});
}
}
And then there is second layout activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".ListActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:id="#+id/input">
<EditText
android:id="#+id/editText_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Add" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_above="#+id/input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
And this activity is connected to ListActivity:
package com.example.listview2;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class ListActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Please Enter Item");
return false;
} else {
return true;
}
}
}
The idea of app is very simple. When you start the app, it start MainActivity which is button with ListView. Then you press button to open ListActivity to create new ListView item and this is my question: how can I add to ListView an item from another Activity?
I think you got the logic a little bit messed up there. For example, you are referencing in ListActivity a view that does not exist in its layout:
lvItem = (ListView)this.findViewById(R.id.listView_items);
listView_items is defined in first.xml layout, which means that the lvItem reference in ListActivity will be null.
In any case, here is a better way to design your app:
1- Have your MainActivity act as the central component of the app. Since it is displaying the listView, it should also be responsible of adding/removing items from it. MainActivity would then start ListActivity when a user wants to add a new item to the list.
2- Have your ListActivity act as a simple interface to get the user's information, and retuning it to your MainActivity.
In this case, the solution is to use startActivityForResult(). Here is a small rewrite to make it work:
public class MainActivity extends Activity {
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button but = (Button) findViewById(R.id.but);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListActivity.class);
startActivityForResult(intent, 1);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
itemArrey.add(0,result);
itemAdapter.notifyDataSetChanged();
}
else if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
}
Now, for ListActivity, you will keep the same code, but add the following in your btnAdd onClickListener:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",etInput);
setResult(RESULT_OK,returnIntent);
finish();
You obviously will want to add input verification and other niceties.
First of all you cannot be doing
lvItem = (ListView)this.findViewById(R.id.listView_items);
you will get Null Pointer exception when lvItem is used as listView_items does not exist in your activity_main layout.
The right way to make your design work is to send "itemArrey" back as bundle extra in the intent you create for setResult.

buttons in listview help?

I need to put button into list view to go to another view.
my button: AddTime = (Button) findViewById(R.id.Add_Time);
i tryd to get it working using:
public class myclass extends ListActivity implements OnClickListener {
and i have
public void onClick(View arg0) {
}
and i need it to go to another place i think using this
Intent intent = new Intent(this, myclass.class);
startActivity(intent);
how to i get this all working in listview?
use this
package example.buttonWithList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class buttonWithList extends ListActivity {
/** Called when the activity is first created. */
String[] items={"azhar","j"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new bsAdapter(this));
}
public class bsAdapter extends BaseAdapter
{
Activity cntx;
public bsAdapter(Activity context)
{
// TODO Auto-generated constructor stub
this.cntx=context;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return items.length;
}
#Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return items[position];
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return items.length;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View row=null;
// TODO Auto-generated method stub
/*if(convertView==null)
{
}*/
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.row, null);
TextView tv=(TextView)row.findViewById(R.id.txtRow);
Button btn=(Button)row.findViewById(R.id.btnRow);
tv.setText(items[position]);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onListItemClick(this, this, position, null);
}
});
return row;
}
protected void onListItemClick(OnClickListener onClickListener,
OnClickListener onClickListener2, int position, Object object) {
// TODO Auto-generated method stub
//Toast.makeText(this, items[position], 3000);
System.out.println(items[position]);
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="#string/hello" />
<ListView android:id="#android:id/list" android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
row.xml
<?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">
<TextView android:text="#+id/TextView01" android:id="#+id/txtRow"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<Button android:id="#+id/btnRow" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Click "></Button>
</LinearLayout>
I suggest you to use a list view with strings. Make a buttons array and when you click on one, via onClick get the button in the array with the position parameter

Categories

Resources