Issue while using contextmenu with listview items in a popupwindow - android

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>

Related

Clicking on EditText does absolutely nothing and cursor stays at end

How do I get it to open up the keyboard on click and change the cursor position when the user clicks within the text? I'm sure it's something simple, but I've tried setting focusable and focusableInTouchMode to true, enabled, textIsSelectable, and nothing has worked. Have also tried using the following in my code:
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(typeField, 0);
My .xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_chat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/softGreen"
android:textColor="#color/darkBlue"
android:windowSoftInputMode="stateAlwaysVisible"
tools:context="com.angelwing.buddyup.ChatActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/softBlue"
android:title="Hey"
app:theme="#style/MyTheme"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:hint="Sample Text"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/sendButton"
android:layout_toStartOf="#+id/sendButton"
android:paddingLeft="5dp"
android:id="#+id/typeField"/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:src="#drawable/edittext_border"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/typeField"
android:clickable="true"
android:onClick="send"
android:id="#+id/sendButton" />
<ToggleButton
android:textOn="Sun"
android:textOff="Sun"
android:layout_width="#dimen/weekend_toggle_button_width"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:id="#+id/sundayButton" />
<ToggleButton
android:textOn="M"
android:textOff="M"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/sundayButton"
android:layout_toRightOf="#+id/sundayButton"
android:layout_toEndOf="#+id/sundayButton"
android:layout_marginRight="-3dp"
android:layout_marginLeft="-3dp"
android:id="#+id/mondayButton" />
<ToggleButton
android:textOn="T"
android:textOff="T"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/mondayButton"
android:layout_toRightOf="#+id/mondayButton"
android:layout_toEndOf="#+id/mondayButton"
android:layout_marginRight="-3dp"
android:id="#+id/tuesdayButton" />
<ToggleButton
android:textOn="W"
android:textOff="W"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tuesdayButton"
android:layout_toRightOf="#+id/tuesdayButton"
android:layout_toEndOf="#+id/tuesdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/wednesdayButton" />
<ToggleButton
android:textOn="Th"
android:textOff="Th"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/wednesdayButton"
android:layout_toRightOf="#+id/wednesdayButton"
android:layout_toEndOf="#+id/wednesdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/thursdayButton" />
<ToggleButton
android:textOn="F"
android:textOff="F"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thursdayButton"
android:layout_toRightOf="#+id/thursdayButton"
android:layout_toEndOf="#+id/thursdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/fridayButton" />
<ToggleButton
android:textOn="Sat"
android:textOff="Sat"
android:layout_width="#dimen/weekend_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/fridayButton"
android:layout_toRightOf="#+id/fridayButton"
android:layout_toEndOf="#+id/fridayButton"
android:layout_marginRight="3dp"
android:id="#+id/saturdayButton" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_below="#+id/sundayButton"
android:layout_above="#+id/edittext"
android:id="#+id/messageListView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"
android:textSize="13dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/toolbar"
android:layout_alignBottom="#+id/saturdayButton"
android:layout_toRightOf="#+id/saturdayButton"
android:layout_toEndOf="#+id/saturdayButton"
android:layout_marginLeft="2dp"
android:layout_marginRight="4dp"
android:id="#+id/setButton" />
</RelativeLayout>
My java file:
package com.angelwing.buddyup;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class ChatActivity extends AppCompatActivity {
Toolbar bar;
SharedPreferences sp;
Button sendButton;
EditText typeField;
String otherUserID;
String buddyID;
String buddyName;
String thisUserName;
String thisUserID;
ChatArrayAdapter adapter;
ArrayList<Message> allMessages;
DatabaseReference convoRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
// sendButton = (Button) findViewById(R.id.sendButton);
// typeField = (EditText) findViewById(R.id.typeField);
//
// View view = this.getCurrentFocus();
// if (view != null)
// {
// InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// im.showSoftInputFromInputMethod(view.getWindowToken(), 0);
// }
//
// sp = getSharedPreferences("com.angelwing.buddyup", Context.MODE_PRIVATE);
//
// Bundle buddyInfo = getIntent().getExtras();
//
// otherUserID = buddyInfo.getString("otherUserID");
// buddyID = buddyInfo.getString("buddyID");
// buddyName = buddyInfo.getString("buddyName");
//
// thisUserID = buddyInfo.getString("thisUserID");
// thisUserName = buddyInfo.getString("thisUserName");
//
// bar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(bar);
// getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setTitle(buddyName);
// Get allMessages from "Conversations" -> buddyID
// allMessages = new ArrayList<>();
// convoRef = FirebaseDatabase.getInstance().getReference("Conversations").child(buddyID);
//
// ListView messagesList = (ListView) findViewById(R.id.messageListView);
// adapter = new ChatArrayAdapter(getApplicationContext(), allMessages);
// messagesList.setAdapter(adapter);
//
// // Add new messages to allMessages
// convoRef.addChildEventListener(new ChildEventListener() {
// #Override
// public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//
// allMessages.add(dataSnapshot.getValue(Message.class));
// adapter.notifyDataSetChanged();
// }
//
// #Override
// public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//
// }
//
// #Override
// public void onChildRemoved(DataSnapshot dataSnapshot) {
//
// }
//
// #Override
// public void onChildMoved(DataSnapshot dataSnapshot, String s) {
//
// }
//
// #Override
// public void onCancelled(DatabaseError databaseError) {
//
// }
// });
}
public void send(View view)
{
Log.i("Clicked", "Yuppers");
// String chat = typeField.getText().toString();
// chat = truncate(chat);
//
// Message newMessage = new Message(thisUserName, chat, thisUserID);
// convoRef.push().setValue(newMessage);
//
// typeField.setText("");
}
public String truncate (String str)
{
return str;
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.mymenu, menu);
return true;
}
public boolean profileClicked (MenuItem item)
{
Intent intent = new Intent(getApplicationContext(), ProfileScreen.class);
startActivity(intent);
return true;
}
public boolean settingsClicked (MenuItem item)
{
return true;
}
public boolean signOutClicked (MenuItem item)
{
sp.edit().putBoolean("signedIn", false).apply();
// auth.signOut();
Intent intent = new Intent(getApplicationContext(), SignInScreen.class);
startActivity(intent);
return true;
}
}
My activity extends AppCompatActivity, if that's important.
Once I click the back button to make the keyboard disappear, I can't make it reappear when I click inside the EditText. Another thing I can't do is move the cursor when I tap inside a String I've already written so if I messed up somewhere, I have to delete text and retype. It's just so frustrating because I have an EditText in another file that works fine and I didn't have to do anything special. The keyboard is opened when I first enter the activity, which is great.
I'm fairly new to Android development so please put things in simple terms, if possible. Thank you so much!
Try this code it may help you solve your problem...
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class AndroidExternalFontsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromInputMethod(view.getWindowToken(), 0);
}
}
}

How to pass value from a method to another method

import android.support.v4.app.Fragment;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.NumberPicker.OnValueChangeListener;
public class MainActivity extends Activity implements OnValueChangeListener {
EditText push_ups, sit_ups;
NumberPicker np;
Button calculate;
final Context context = this;
CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calculate = (Button)findViewById(R.id.calculate);
push_ups = (EditText)findViewById(R.id.pushups);
sit_ups = (EditText)findViewById(R.id.situps);
np = (NumberPicker)findViewById(R.id.np1);
checkbox = (CheckBox)findViewById(R.id.checkbox);
String[] values = {"some array"};
np.setMaxValue(values.length-1);
np.setMinValue(0);
np.setDisplayedValues(values);
np.setWrapSelectorWheel(false);
//calculateButton runs when I click the "calculate" Button
calculateButton();
LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout1);
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
hideKeyboard();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
}
private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(push_ups.getWindowToken(), 0);
}
public int calculatePushups() {
int pushupScore = 0;
int ageGroup = Integer.parseInt(null, np.getValue());
int pushupReps = Integer.parseInt(push_ups.getText().toString());
final int [][] pushupTable = {"some 2D array"};
if (pushupReps<= 60) {
pushupScore = pushupTable[pushupReps][ageGroup];
} else {
pushupScore = 60;
}
return pushupScore;
}
public int calculateSitups() {
final int [][] situpTable = {"some 2D array"};
return 0;
}
private void normalRun() {
}
private void specialRun() {
}
private void calculateRun() {
if (checkbox.isChecked()) {
specialRun();
}
else {
normalRun();
}
}
private void calculateScore() {
calculatePushups();
calculateSitups();
calculateRun();
}
public void calculateButton() {
final TextView pus = (TextView)findViewById(R.id.pushup_score);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_custom);
dialog.setTitle("Score");
I am trying to set the TextView to display the pushupScore here but it seems I am trying to pass a result from another method to this. I have no idea how to get it around still new with android,
//pus.setText(pushupScore);
pus.setText(String.valueOf(calculatePushups()));
Button dialogButton = (Button) dialog.findViewById(R.id.dialog_ok);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
Here's my dialog XML code:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Push-ups: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/pushup_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.97"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Sit-ups: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="2.4km Run: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:text="Award: "
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/dialog_ok"
style="#style/AppTheme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:lineSpacingExtra="5dp"
android:text="Ok" />
</LinearLayout>
you are returning the pushupScore in calculatePushups so just write:
pus.setText(String.valueOf(calculatePushups()));
And btw this is not a android mechanism, this is simple java return usage:
http://docs.oracle.com/javase/tutorial/java/javaOO/returnvalue.html
You left out quite a bit of your code so I'm not sure where your problem is, but if you could follow these steps and let me know if you're getting any errors etc? Anyway, here is what you need to have:
Make sure your Activity implements OnClickListener:
public class MainActivity extends Activity implements OnClickListener, OnValueChangeListener {
//...
}
Within the activity's overridden onCreate() method, register the activity as the handler:
calculate = (Button)v.findViewById(R.id.dialog_ok);
calculate.setOnClickListener(this);
Within MainActivity, have the handler like so:
public void onClick(View v){
switch(v.getId(){
case R.id.dialog_ok:
push_ups.setText("" + calculatePushups());
break;
}
// ...
}
Perhaps you should change your EditText into a TextView, the EditText isn't necessary and might be causing problems?
Is this what you were after?

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);

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.

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