Android java.lang.NullPointerException at FindViewById in a dialog - android

I saw many similar questions to this but still cannot resolve mine.
Here is the log:
01-26 00:30:49.714: ERROR/AndroidRuntime(616): FATAL EXCEPTION: main
java.lang.NullPointerException
at com.app.newItemList.onDialogPositiveClick(newItemList.java:39)
at com.app.itemDialog$2.onClick(itemDialog.java:39)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Here is the relevant Java files:
package com.app;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Aljarhi
* Date: 1/24/13
* Time: 10:22 PM
* To change this template use File | Settings | File Templates.
*/
public class newItemList extends FragmentActivity
implements itemDialog.NoticeDialogListener{
public void showNoticeDialog() {
// Create an instance of the dialog fragment and show it
DialogFragment dialog = new itemDialog();
dialog.show(getFragmentManager(), "NoticeDialogFragment");
}
// The dialog fragment receives a reference to this Activity through the
// Fragment.onAttach() callback, which it uses to call the following methods
// defined by the NoticeDialogFragment.NoticeDialogListener interface
#Override
public void onDialogPositiveClick(DialogInterface dialog, int id) {
// User touched the dialog's positive button
EditText et = (EditText) findViewById(R.id.editText1);
adapter.add(et.getText().toString());
}
#Override
public void onDialogNegativeClick(DialogInterface dialog, int id) {
// User touched the dialog's negative button
dialog.cancel();
}
ArrayAdapter<String> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_list);
ListView lvc = (ListView) findViewById(R.id.listView3);
adapter = new ArrayAdapter<String>(this, R.id.textView2, new ArrayList<String>());
lvc.setAdapter(adapter);
}
public void addItem(View clickedButton)
{
showNoticeDialog();
}
}
package com.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.EditText;
/**
* Created with IntelliJ IDEA.
* User: Aljarhi
* Date: 1/25/13
* Time: 3:11 PM
* To change this template use File | Settings | File Templates.
*/
public class itemDialog extends DialogFragment
{
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogInterface dialog, int id);
public void onDialogNegativeClick(DialogInterface dialog, int id);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_item, null))
// Add action buttons
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(dialog, id);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogNegativeClick(dialog, id);
}
});
return builder.create();
}
// Use this instance of the interface to deliver action events
NoticeDialogListener mListener;
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
}
here is the relevant xml files:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="vertical" android:gravity="center_horizontal|top">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mezzo List"
android:id="#+id/textView2" android:layout_gravity="center_horizontal|top"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="263dp"
android:id="#+id/listView3" android:layout_gravity="center_horizontal|top" android:choiceMode="none"/>
<Button
android:layout_width="81dp"
android:layout_height="wrap_content"
android:text="Add Item"
android:id="#+id/button4" android:onClick="addItem"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="25dp"
android:text="Mezzo List"
android:id="#+id/textView4" android:layout_gravity="center"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Item Name:"
android:id="#+id/textView5" android:layout_gravity="center" android:textSize="20dp"/>
<EditText
android:layout_width="205dp"
android:layout_height="wrap_content"
android:text="New EditText"
android:id="#+id/editText1" android:layout_gravity="center" android:inputType="text"
android:hint="Item Name"
/>
</LinearLayout>
I found the problem to be in the edittext1 id not recognised or as an edittext although it appeared in the list of choices and I selected it form there. I am using intellij Idea 12.0.2. Any help will be appreciated. Thanks in advance.

Actually, I found the solution to my problem.
Inorder to for findViewById to work correctly you have first to select the view which inflates or has its content first set to the corresondong xml file. So, here is the solution:
final View textEntryView = inflater.inflate(R.layout.dialog_item, null);
EditText et = (EditText) textEntryView.findViewById(R.id.editText1);
Thanks all for your help.

In this line:
adapter = new ArrayAdapter<String>(this, R.id.textView2, new ArrayList<String>());
You probably don't want R.id.textView2 there. You generally want to pass in a layout which contains a textview (with the other id parameter). e.g.
adapter = new ArrayAdapter<String>(this, R.layout.somelayout, R.id.someTextViewInThatLayout, new ArrayList<String>());

Related

Android studio APP has stopped

I am new in android learning. Using Android Studio. My app name is Design1. I am learning events so created a event page with two buttons for testing two events, one is toast and another is Alert dialog box.The Toast is working fine but when I click ALERT button to show the alert dialog then a message comes ie "Design1 has stopped".
If I remove the showAlert event from activity_events.xml and events.java files then my works perfect.
events.java
package com.example.borntoflirt.design1;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class events extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
}
public void showToast(View v) {
Context context = getApplicationContext(); // OR getBaseContext()
CharSequence text = "Hi Toast";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
public void showAlert(View v) {
Context context1 = getApplicationContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context1);
builder.setMessage("Write your message here.");
builder.setCancelable(true);
builder.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
activity_events.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_red_light"
android:isScrollContainer="false"
android:orientation="vertical"
android:paddingLeft="15dp"
android:paddingRight="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:layout_weight=".30"
android:background="#drawable/rounded_button"
android:text="Toast"
android:textColor="#000"
android:onClick="showToast"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:text="Alert"
android:textColor="#000"
android:background="#drawable/rounded_button"
android:layout_margin="2dp"
android:onClick="showAlert"/>
</LinearLayout>
</LinearLayout>
You need to use Activity context. If you use application context, the IllegalStateExpetion will be thrown.
...
new AlertDialog.Buidler(this) // this is a Activity, which is a Context's subclass
....
Use Activity's Context :
AlertDialog.Builder builder = new AlertDialog.Builder(event.this);
Instead Of
Context context1 = getApplicationContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context1);
Try to use getActivity() instead of getApplicationContext().
It has been 7 months but none of the answers worked on me. So this is solution that i found. Try MainActivity.this instead of getApplicationContext() or this.

scrollview not responding

In one screen in my app, I have one ListFragment that is not responding to gestures. In other screens, my ListFragments behave appropriately - moving up and down based on touch. But this instance does not move in response to gestures. I have tried setting the height to a specific dip, enclosing the ListFragment in a ScrollView but nothing works. Logs prove there are 3 entries in the list but only the first one and half of the second are visible. I can select the first entry from the list.
The xml follows. It's the inner fragment identified by " android:name="com.chex.control.LabelList"" that is not scrolling.
Has anyone encountered this problem and solved it?
Thanks
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/new_interval_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Interval" />
<EditText
android:id="#+id/days_in_interval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="days in interval"
android:inputType="number"
android:singleLine="true" />
<EditText
android:id="#+id/goodi_goal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="goodi goal"
android:inputType="number"
android:singleLine="true" />
<LinearLayout
android:id="#+id/label_selector"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/default_label_pane"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Default Labels" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical" >
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/default_labels_fragment"
android:name="com.chex.control.LabelList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:focusable="true" >
</fragment>
</ScrollView>
</LinearLayout>
<LinearLayout
android:id="#+id/add_remove_label_selector"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android:id="#+id/add_label_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add" />
<Button
android:id="#+id/remove_label_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Remove" />
</LinearLayout>
<LinearLayout
android:id="#+id/label_pane"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inteval Labels" />
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/interval_labels_fragment"
android:name="com.chex.control.IntervalLabelList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true" >
</fragment>
<EditText
android:id="#+id/new_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="new label"
android:inputType="text"
android:singleLine="true" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/keep_discard_button_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/keep_interval_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Keep" />
<Button
android:id="#+id/discard_interval_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Discard" />
</LinearLayout>
</LinearLayout>
</ScrollView>
here is the fragment .java
package com.chex.control;
import java.util.ArrayList;
import com.chex.R;
import com.chex.storage.Child;
import com.chex.storage.DatabaseConstants;
import com.chex.storage.DatabaseHelper;
import com.chex.storage.DatabaseIO;
import com.chex.storage.Label;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* presents all the labels on the device.
*/
public class LabelList extends ListFragment implements DatabaseConstants,
GoodiList {
private final String TAG = "LabelList";
ArrayAdapter<Label> adapter = null;
private ListParent parentActivity;
private Label[] values;
private Label currentItem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "on Create");
ArrayList<Label> labelList = Label.getLabelsForInterval();
Log.i(TAG,labelList.size()+" labels");
// adapter = new IntervalListAdapter(getActivity(), values);
adapter = new IntervalListAdapter(getActivity(), labelList);
setListAdapter(adapter);
Log.e(TAG, "finished on Create");
}
/*
* (non-Javadoc)
*
* #see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
LongClickListener longClickListener = new LongClickListener();
getListView().setOnItemLongClickListener(longClickListener);
}
/**
* create and return a CursorLoader that will take care of creating a Curso
* for the data being displayed.
*/
/**
* this used to delete. However, we need it to select usually. Now delete is
* done by long click.
*/
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// delete child - remove child from list and database
Object item = l.getItemAtPosition(position);
currentItem = (Label) item;
Log.e(TAG,
"selected " + currentItem.getLabel() + " id: "
+ currentItem.getId() + " at position " + position);
parentActivity.listItemSelected(this, position, currentItem.getId());
}
/**
* Forces cursor to requery database and list to be update. Used when a new
* child is entered in parent activity's EditText field.
*/
public void notifyDataChanged() {
Log.e(TAG, "told adapter that data changed");
adapter.notifyDataSetChanged();
}
/*
* (non-Javadoc)
*
* #see android.support.v4.app.Fragment#onAttach(android.app.Activity)
*/
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
parentActivity = (ListParent) activity;
parentActivity.setList(this);
}
class LongClickListener implements OnItemLongClickListener {
public boolean onItemLongClick(AdapterView<?> adapterView, View view,
int position, long id) {
// delete child - remove child from list and database
// adapter view. Can always call parent's getItemAtPosition
final Object item = adapterView.getItemAtPosition(position);
final Label label = (Label) item;
final String name = label.getLabel();
Log.e(TAG, "selected " + name + " at position " + position
+ " now we'll delete them");
// make sure user wants to delete
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Delete " + name + "?");
alert.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Label.deleteLabel(name);
adapter.remove(label);
// update the list
notifyDataChanged();
}
});
alert.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// nothing happens - child remains
}
});
alert.show();
return true;
}
}
#Override
public void addListItem(int itemId) {
Label labelToAdd = Label.lookupLabel(itemId);
if (labelToAdd == null) {
Log.e(TAG, "didn't find a label for label id " + itemId);
} else {
Log.e(TAG, "adding label: " + labelToAdd.getLabel() + " "
+ labelToAdd.getId() + " id argument: " + itemId);
// breaks because the adapter is currently strings
adapter.add(labelToAdd);
notifyDataChanged();
}
}
#Override
public void removeListItem(int itemId) {
// TODO Auto-generated method stub
}
#Override
public void removeListItem() {
// TODO Auto-generated method stub
}
#Override
public void highlightListIndex(int index) {
ListView listView = getListView();
listView.setItemChecked(index, true);
}
}
The android is not the best with scrolling views in scrolling views, like in your case.
You have to try to avoid this situation, try to modify the layout to avoid these conflicts.
A pain in the a** method would be to intercept the parent's touch event (add an gesture listener too) and pass the event to the listfragment when the user made the scroll on the listfragment (you have to know the coordinates of the fragment inside the screen, etc). It sounds a lot easier then as is and will cause a lot of issues after that, so i recommend to rewrite your layout instead.

Multiple TextViews Added in Loop onClick Unexpected Behavior

I have two RelativeLayouts that I am programmatically adding TextViews to from an ArrayList with the intent that, based on the TextView clicked, I can index back into the original ArrayList. For my trivial code example, I'm arbitrarily splitting the items into the two RelativeLayouts.
The code works as expected when the first TextView is clicked. The dialog shows up displaying the correct word and index. However, after closing the dialog, if a different TextView is clicked, the word and index (testWord and testID in my code example) are not updated and only the first TextView's information is displayed. It seems that onClick is only being called on the first click.
Here is an example Java class (I apologize for any formatting errors, it's my first time posting here):
package com.test.test;
import java.util.ArrayList;
import java.util.Scanner;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class AndTestActivity extends Activity {
private final int DIALOG_CASE_ITEM_SELECT=0,CURR_ID=128,P_ID=256,P_HR=512,C_HR=1024;
private final String TEST="This is a test. Only a test.";
private int numPast,testID;
private String testWord;
private ArrayList<String> test;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Scanner s=new Scanner(TEST);
test=new ArrayList<String>();
while(s.hasNext()){
test.add(s.next());
}
int currID=CURR_ID,pID=P_ID,pHrID=P_HR,cHrID=C_HR,tempLen=3;
numPast=0;
RelativeLayout rlP=(RelativeLayout)findViewById(R.id.caseItemListPastLayout);
RelativeLayout rlC=(RelativeLayout)findViewById(R.id.caseItemListCurrLayout);
for(int x=0;x<test.size();x++){
if(x>tempLen){
addToRL(test.get(x),true,rlC,currID,cHrID);
currID++;
cHrID++;
}else{
numPast++;
addToRL(test.get(x),false,rlP,pID,pHrID);
pID++;
pHrID++;
}
}
}
private void addToRL(String sb, boolean current,RelativeLayout rl,int id,int hrID){
TextView citv=new TextView(this);
citv.setText((CharSequence)sb);
citv.setMovementMethod(new ScrollingMovementMethod());
citv.setTextSize(15);
citv.setTextColor(Color.BLACK);
citv.setGravity(Gravity.CENTER_HORIZONTAL);
if(current){
citv.setBackgroundColor(Color.RED);
}else{
citv.setBackgroundColor(Color.WHITE);
}
citv.setPadding(20, 10, 20, 10);
citv.setWidth((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 360, getResources().getDisplayMetrics()));
citv.setId(id);
RelativeLayout.LayoutParams cilp=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
if(current&&id!=CURR_ID)cilp.addRule( RelativeLayout.BELOW, hrID-1);
else{
if(id!=P_ID)cilp.addRule( RelativeLayout.BELOW, hrID-1);
}
citv.setLayoutParams(cilp);
citv.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
TextView tv0=(TextView)v;
int tvID=tv0.getId()-P_ID;
if(tvID<0){
tvID=(tv0.getId()-CURR_ID)+numPast;
}
testID=tvID;
testWord=test.get(testID);
showDialog(DIALOG_CASE_ITEM_SELECT);
}
});
rl.addView(citv);
View hr=new View(this);
hr.setBackgroundColor(getResources().getColor(R.color.background));
RelativeLayout.LayoutParams hrlp=new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, 5);
hrlp.addRule(RelativeLayout.BELOW,id);
hr.setLayoutParams(hrlp);
hr.setId(hrID);
rl.addView(hr);
}
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
switch(id){
case DIALOG_CASE_ITEM_SELECT:
builder = new AlertDialog.Builder(this);
builder.setMessage("word: "+testWord+" index: "+testID)
.setCancelable(true)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}
}
Here is the associated XML for the layout (nothing special, but I thought I'd include it so there's a fully working example):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_height="wrap_content" android:layout_width="wrap_content" android:orientation="vertical"
android:background="#color/background"
android:screenOrientation="portrait">
<ScrollView
android:id="#+id/caseItemCurrScroll"
android:fillViewport="true"
android:padding="10dp"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<RelativeLayout android:id="#+id/caseItemListCurrLayout"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
</RelativeLayout>
</ScrollView>
<View
android:id="#+id/caseItemScrollSpacer"
android:layout_width="fill_parent"
android:layout_below="#id/caseItemCurrScroll"
android:layout_height="5dp"
android:background="#color/background"/>
<ScrollView
android:id="#+id/caseItemPastScroll"
android:fillViewport="true"
android:padding="10dp"
android:layout_below="#id/caseItemScrollSpacer"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<RelativeLayout android:id="#+id/caseItemListPastLayout"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
</RelativeLayout>
</ScrollView>
</RelativeLayout>
That should be a fully "working" example, with the addition of
<color name="background">#3E3E3E</color>
in the strings.xml
onCreateDialog() is only called once, while onPrepareDialog() is called each time the Dialog opens.
Override onPrepareDialog() and call ((AlertDialog) dialog).setMessage() here.

Back button in dialog

Am trying to get the back button in my dialog to go back to the original screen. I don't know if I have all the imports that I need. Can someone tell me where I am going wrong?
Java code:
package my.dlog;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
public class DlogActivity extends Activity {
/** Called when the activity is first created. */
Dialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dialog = new Dialog(this);
dialog.setContentView(R.layout.main2);
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onBackPressed() {
Intent intent = new Intent(DlogActivity.this, DlogActivity.class);
startActivity(intent);
finish();
}
public void onClick(View v) {
dialog.show();
}
});
}
}
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:minHeight="400dp"
android:minWidth="300dp" android:background="#drawable/mint1">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<ImageView
android:layout_width="236dp"
android:layout_height="220dp"
android:layout_marginRight="100dp" android:background="#drawable/carsee"/>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</RelativeLayout>
</LinearLayout>
b.setOnClickListener(new OnClickListener() {
public void onBackPressed() {
dialog.cancel();
// Simply Dismiss the dialog to make it close and return to back..
/*What you are using is not a valid construct */
}
Also make sure that button1 in in main layout as you have used findViewById(R.id.button1) directly for set content view
Well normally the back button works just without any help from us. If you take the
public void onBackPressed() {
Intent intent = new Intent(DlogActivity.this, DlogActivity.class);
startActivity(intent);
finish();
}
out, what happens when you press 'back'? If this is not what you want, then what do you wnat to happen? If there are no errors, I would think you have the required imports.
Cliff

dialog code wrong somewere?

Can someone help with this code. what am looking for is for the button on my dialog to go back a pagewhen the users press the button.so i dont have to press the phone back button thank you.
java file
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
public class DlogActivity extends Activity {
/** Called when the activity is first created. */
Dialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dialog = new Dialog(this);
dialog.setContentView(R.layout.main2);
dialog.setTitle("This is my custom dialog box");
dialog.setCancelable(true);
Button b=(Button)findViewById(R.id.button1);
#SuppressWarnings("unused")Button button01 =(Button)findViewById(R.id.btn2);
Intent intent = new Intent(DlogActivity.this, DlogActivity.class);
startActivity(intent);
finish();
b.setOnClickListener(new OnClickListener() {
public void onBackPressed() {
dialog.cancel();
// Simply Dismiss the dialog to make it close and return to back..
/*What you are using is not a valid construct */
}
public void onClick(View v) {
dialog.show();
}
});
}
}
xml.code
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="Button" />
<ImageView
android:layout_width="236dp"
android:layout_height="220dp"
android:layout_marginRight="100dp" android:background="#drawable/carsee"/>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</RelativeLayout>
</LinearLayout>
seems like the problem is at below code,
dialog.setContentView(R.layout.main2);
you cannot give layout like this, instead you need to inflate layout to your dialog.

Categories

Resources