Adding ListView item from another Layout - android

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.

Related

Button not working in android app?

I'm building an app which has 3 functions a converter, a calculator and a notes section. When I click on the converter button on the home page it brings me to the converter activity / page. But when I click on the calculator button on the home page it won't open. Here is the code below. Any reason as to why? Thanks in advance.
MainActivity
package com.qub.buildersbuddy;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button buttonConverter;
Button buttonCalculator;
Button buttonNotePad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button ConvertBtn = (Button) findViewById(R.id.butonConverter);
ConvertBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,CentInch.class);
startActivity(intent);
}
});
}
public void setupConverterButton(){
buttonConverter = (Button) findViewById(R.id.butonConverter);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void CentToInch(){
buttonConverter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class centClass = Class
.forName("com.qub.buildersbuddy.CentInch");
Intent myintent = new Intent(MainActivity.this,centClass);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
protected void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button CalcBtn = (Button) findViewById(R.id.buttonCalc);
CalcBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Calculator.class);
startActivity(intent);
}
});
}
public void setupCalculatorButton(){
buttonCalculator = (Button) findViewById(R.id.buttonCalc);
// Button messageButton = (Button) findViewById(R.id.butonConverter);
}
public void Calculator(){
buttonCalculator.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opening the
try{
Class calcClass = Class
.forName("com.qub.buildersbuddy.Calculator");
Intent myintent = new Intent(MainActivity.this,calcClass);
startActivity(myintent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
});
}
}
activity_main:
<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=".CentInch" >
<Button
android:id="#+id/butonConverter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp"
android:text="Converter" />
<Button
android:id="#+id/buttonCalc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/butonConverter"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:text="Calculator" />
<Button
android:id="#+id/buttonNotes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/buttonCalc"
android:layout_centerHorizontal="true"
android:layout_marginTop="31dp"
android:text="Notes" />
</RelativeLayout>
Is this the exact code you're using? Your #onCreate1 method will never get called. #onCreate gets called because it overrides a method from the class you extended (Activity), and something in Activity calls the method when the activity first starts. Move your calculator button logic into the first #onCreate method.

Bundle savedInstanceState is null on onCreate() although savedInstanceState is already set data

I have a problem when getting state of activity. I have 2 activities: MainActivity and Activity2. In MainActivity I have put an editText and a button name GO. In Activity2, I have a button name BackMainActivity. What I want is that: I put a text, for example:"abc" into EditText then click button GO. App will navigate to Activity2. After that, I click button BackMainActivity, app will navigate to MainActivity and data in EditText is restore as "abc".
I already used onSaveInstanceState and onRestoreInstanceState. App run through onSaveInstanceState before going to Activity2. But if I go back to MainActivity, onCreate(), savedInstanceState is null. Can you show me the reason ? I want to store data of mainActivity in bundle. So how can I do ? Thank you very much !
MainActivity
package com.example.demosavedataactivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText t;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, Activity2.class);
startActivity(intent);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
String a = t.getText().toString();
outState.putString("text",a);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
t.setText(savedInstanceState.getString("text"));
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
Log.w("<<<<<<<<<<<<<<<<<<<", "onDestroy");
super.onDestroy();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
Log.w("<<<<<<<<<<<<<<<<<<<", "onPause");
super.onPause();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
Log.w("<<<<<<<<<<<<<<<<<<<", "onRestart");
super.onRestart();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
Log.w("<<<<<<<<<<<<<<<<<<<", "onResume");
super.onResume();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
Log.w("<<<<<<<<<<<<<<<<<<<", "onStart");
super.onStart();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
Log.w("<<<<<<<<<<<<<<<<<<<", "onStop");
super.onStop();
}
}
Activity2
package com.example.demosavedataactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Activity2 extends Activity {
Button back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
back = (Button) findViewById(R.id.button1);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Activity2.this, MainActivity.class);
startActivity(intent);
}
});
}
}
activity2.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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CombackA1" />
</LinearLayout>
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=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="18dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginLeft="50dp"
android:layout_marginTop="63dp"
android:text="Button" />
</RelativeLayout>
Just do something like:
1: Fetch data from onSavedInstanceState in your oncreate() and put it in your edittext. Something like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
/*Just fetch data from savedInstanceState */
if(savedInstanceState != null){
t.setText(savedInstanceState.getString("text"));
}
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Activity2.class);
startActivity(intent);
}
});
}
And in your Activity2 set a FLAG_ACTIVITY_REORDER_TO_FRONT flag with your intent.like:
Intent intent = new Intent(Activity2.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
For a better idea just check this conversation.
In the onClick function of your Activity2 you don't go back to the previous MainActivity but you open a new MainActivity.
Just finish Activity2 by calling finish() then your first MainActivity will come up again. It should be working with the hardware back button of your device.

Cannot read EditText in fragment class

I have two tabs and each tab is a Fragment. In one of the fragments (Afragment.claas) I have a dialog box to insert some data, and I want to save them in a database. When I fill the text fields and press OK, the application stops.
I think when I initialize the edittext there is something wrong.
name = (EditText) activity.findViewById(R.id.etProviderName);
The above statement is returning null
Here is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Afragment extends ListFragment {
DBAdapter db;
Activity activity;
private static final String fields[] = { "provider._providerName", "_providerMobile" };
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initAdapter();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
add();
return (true);
case R.id.menu_reset:
initAdapter();
return (true);
case R.id.menu_info:
Toast.makeText(activity, "Developed By Omar Al-Shammary", Toast.LENGTH_LONG)
.show();
return (true);
}
return (super.onOptionsItemSelected(item));
}
private void add() {
// TODO Auto-generated method stub
System.out.println("insider Add Method");
final View addView = activity.getLayoutInflater().inflate(R.layout.add_provider, null);
new AlertDialog.Builder(activity).setTitle("Add a Provider").setView(addView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
System.out.println("Befor calling insert in providers");
insertInProviders();
System.out.println("after calling insert in providers");
}
}).setNegativeButton("Cancel", null).show();
initAdapter();
}
private void initAdapter() {
activity = getActivity();
db = new DBAdapter(activity);
fillTheList();
}
public void fillTheList()
{
db.open();
Cursor data = db.getAllProviders();
CursorAdapter dataSource = new SimpleCursorAdapter(activity,
R.layout.row, data, fields,
new int[] { R.id.first, R.id.last });
setListAdapter(dataSource);
db.close();
setListAdapter(dataSource);
}
public void insertInProviders()
{
EditText name,location,number;
name = (EditText) activity.findViewById(R.id.etProviderName);
location = (EditText) activity.findViewById(R.id.etProviderName);
number = (EditText) activity.findViewById(R.id.etProviderName);
if(name == null)
System.out.println("EditeText name is null");
String provName = name.getText().toString();
if(location == null)
System.out.println("location is null");
String provLocation = location.getText().toString();
String provNumber = number.getText().toString();
System.out.println("Before Open");
db.open();
System.out.println("Before DB.Insert");
db.insertProvider(provName, provLocation, provNumber);
System.out.println("Before Close");
db.close();
}
}
add_provider.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" >
<TextView
android:id="#+id/tvProviderName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<EditText
android:id="#+id/etProviderName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tvProvLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location" />
<EditText
android:id="#+id/etProvLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvProvNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number" />
<EditText
android:id="#+id/etProvNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
</LinearLayout>
This is the code I use for declaring buttons in Fragments - maybe it can help you.
What I would do is access the inflated layout and then you should be able to access items underneath it. Let me know if that makes sense.
LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button)theLayout.findViewById(R.id.frag1_button);
#Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(), "OnClickMe button clicked", Toast.LENGTH_LONG).show();
}
});
return theLayout;
So maybe you should try this since you inflate your View as "addView"
name = (EditText) addView.findViewById(R.id.etProviderName);
The findViewById should not be called by the activity but by the enclosing view. You should have something like:
In the class
View aView;
In the method:
LayoutInflater inflater = getActivity().getLayoutInflater();
aView = inflater.inflate(R.layout.add_provider, null);
...
EditText name = (EditText) aView.findViewById(R.id.etProviderName);
I hope it helps.

I am unable to set Onclick event on Imageview in android

Where ever i click on ImageView the onclick method is not hapenning. i mean it is not redirecting to my main.xml
//package name : bunk
//My cesem.XML :
//just a Textview and a Image View
- Indented four spaces.
<?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:padding="25dp"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Select Your Semester"
android:textSize="25dp"
android:gravity="center"
android:id="#+id/tvSemCe"
android:layout_marginBottom="20dp"
/>
<ImageView
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/back"
/>
</LinearLayout>
//Class file: Cesem.java
package com.bunk;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class Cesem extends Activity implements OnClickListener{
ImageView back;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cesem); // cesem.xml
back=(ImageView) findViewById(R.id.back);// back is ImageView
back.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == back) {
setContentView(R.layout.main);
}
}
}
if (v.getId() == R.id.back)
instead of
if (v == back)
try to set the element as clickable:
back.setClickable(true);
Or maybe you can't see a feedback beacuse of the content of click callback (setContentView..)
Try to log something inside the click callback, such as
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == back) {
Toast.makeText(this, "Click", Toast.LENGTH_SHORT).show();
setContentView(R.layout.main);
}
}
Change your code as:
public class Cesem extends Activity implements OnClickListener{
ImageView back;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cesem); // cesem.xml
back=(ImageView) findViewById(R.id.back);// back is ImageView
back.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.back) {
Toast.makeText(getApplicationContext(), "Toast 1",Toast.LENGTH_SHORT).show();
Activity.this.setContentView(R.layout.main);
}
else
{
Toast.makeText(getApplicationContext(), "Toast 2",Toast.LENGTH_SHORT).show();
}
}
}
}
and register your Activity in manifest as:
<activity
android:name=".Cesem" />

close custom Dialog 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++
}
}
});

Categories

Resources