Java 从适配器类获取不同活动中的EditText值
我是Android的新手,我正在尝试构建一个货币转换器应用程序。我很难理解如何从CurrencyRateAdapter.java内部访问activity_main.xml中的EditText。我尝试过膨胀视图-代码构建时没有错误,但在选中复选框、输入值,然后按convert后崩溃 编辑Java 从适配器类获取不同活动中的EditText值,java,android,listview,android-arrayadapter,Java,Android,Listview,Android Arrayadapter,我是Android的新手,我正在尝试构建一个货币转换器应用程序。我很难理解如何从CurrencyRateAdapter.java内部访问activity_main.xml中的EditText。我尝试过膨胀视图-代码构建时没有错误,但在选中复选框、输入值,然后按convert后崩溃 编辑 更改了“int amount=mainActivity.getAmount();”至“int amount=activity.getAmount();”它运行时不会崩溃,但应用程序中不会显示结果 生成错误:错误:
更改了“int amount=mainActivity.getAmount();”至“int amount=activity.getAmount();”它运行时不会崩溃,但应用程序中不会显示结果 生成错误:错误:(55,40)错误:无法从静态上下文引用非静态方法getAmount() 我提供了以下代码作为上下文: MainActivity.java
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
CheckBox USchk, UKchk, AUSchk, JAPchk, CHINAchk, SINGchk, THAIchk, INDIAchk;
EditText inputAmount;
Button convertButton;
int count = 0, checkedBoxes = 0;
TextView MYR;
CheckBox[] checkBoxArray;
ArrayList<CurrencyRate> currencyRates;
CurrencyRateAdapter currencyRateAdapter;
ArrayList<CurrencyRate> resultRows;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
inputAmount.setEnabled(false);
checkBoxArray = new CheckBox[]{
(CheckBox)findViewById(R.id.chkUS),
(CheckBox)findViewById(R.id.chkUK),
(CheckBox)findViewById(R.id.chkAUS),
(CheckBox)findViewById(R.id.chkJAP),
(CheckBox)findViewById(R.id.chkCHINA),
(CheckBox)findViewById(R.id.chkSING),
(CheckBox)findViewById(R.id.chkTHAI),
(CheckBox)findViewById(R.id.chkINDIA)
};
for (CheckBox cb: checkBoxArray) {
cb.setOnCheckedChangeListener(cbListener);
}
currencyRates = new ArrayList<CurrencyRate>();
currencyRates.add(new CurrencyRate("USD",4.25,"1 USD = 4.25 MYR"));
currencyRates.add(new CurrencyRate("GBP",5.60,"1 GBP = 5.60 MYR"));
currencyRates.add(new CurrencyRate("AUS",3.30,"1 AUD = 3.30 MYR"));
currencyRates.add(new CurrencyRate("JPY",0.0394,"1 JYP = 0.0394 MYR"));
currencyRates.add(new CurrencyRate("CNY",0.633,"1 CNY = 0.633 MYR"));
currencyRates.add(new CurrencyRate("SGD",3.10,"1 SGD = 3.10 MYR"));
currencyRates.add(new CurrencyRate("THB",0.128,"1 THB = 0.128 MYR"));
currencyRates.add(new CurrencyRate("INR",0.067,"1 INR = 0.067 MYR"));
resultRows = new ArrayList<CurrencyRate>();
//invokeAdapter();
//DECLARE ADAPTER
currencyRateAdapter = new CurrencyRateAdapter(this, resultRows);
ListView listView = (ListView) findViewById(resultListView);
listView.setAdapter(currencyRateAdapter);
}
private View.OnClickListener convertListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
checkedBoxes = countCheckboxes();
Toast.makeText(getApplicationContext(),"CLICKED CONVERT",Toast.LENGTH_SHORT).show();
int crBeforeCalc = currencyRates.size();
String crStrBCalc = Integer.toString(crBeforeCalc);
Log.i("crStrBCalc",crStrBCalc);
resultRows.clear();
//Execute Calculate function
calculateTotal(inputAmount,checkBoxArray,currencyRates);
int crAfterCalc = currencyRates.size();
String crStrACalc = Integer.toString(crAfterCalc);
Log.i("crStrACalc",crStrACalc);
}
};
//Calculate rates
private void calculateTotal(EditText inputAmount,CheckBox checkBoxArray[], ArrayList<CurrencyRate> currencyRates)
{
for(int i = 0; i < 8; i++) {
Log.i("THISTAG", "PRINT TIMES PRINTED LOOP");
if(checkBoxArray[i].isChecked())
{
Log.i("ifRuns","ifRuns");
resultRows.add(currencyRates.get(i));
}
}
//currencyRateAdapter.addAll(resultRows);
int rrDSize = resultRows.size();
String rrDStringSize = Integer.toString(rrDSize);
Log.i("rrDStringSize",rrDStringSize);
//currencyRateAdapter.notifyDataSetChanged();
int rrASize = resultRows.size();
String rrAStringSize = Integer.toString(rrASize);
Log.i("rrAStringSize",rrAStringSize);
}
public void initUI() {
USchk = (CheckBox) findViewById(R.id.chkUS);
UKchk = (CheckBox) findViewById(R.id.chkUK);
AUSchk = (CheckBox) findViewById(R.id.chkAUS);
JAPchk = (CheckBox) findViewById(R.id.chkJAP);
CHINAchk = (CheckBox) findViewById(R.id.chkCHINA);
SINGchk = (CheckBox) findViewById(R.id.chkSING);
THAIchk = (CheckBox) findViewById(R.id.chkTHAI);
INDIAchk = (CheckBox) findViewById(R.id.chkINDIA);
MYR = (TextView) findViewById(R.id.MYR);
convertButton = (Button) findViewById(R.id.convertButton);
inputAmount = (EditText) findViewById(R.id.amountInput);
convertButton.setOnClickListener(convertListener);
}
CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
disableChkWhenMax(checkBoxArray);
inputAmount.setText("");
//Clear all textbox rows
resultRows.clear();
}
};
private void disableChkWhenMax(CheckBox checkBoxes[]){
int countChecked =0;
inputAmount.setEnabled(false);
for (CheckBox cb:checkBoxes){
cb.setEnabled(true);
if (cb.isChecked()) countChecked++;
}
if(1<= countChecked)
{
inputAmount.setEnabled(true);
}
if (3 <= countChecked) {
for (CheckBox cb:checkBoxes){
if (!cb.isChecked())cb.setEnabled(false);
}
}
}
public int getAmount() {
int value=0;
if (inputAmount != null) {
return Integer.parseInt(inputAmount.getText().toString().trim());
} else {
return 0;
}
}
private int countCheckboxes()
{
if (USchk.isChecked()) {
count++;
}
if (UKchk.isChecked()){
count++;
}
if (AUSchk.isChecked()){
count++;
}
if(JAPchk.isChecked()){
count++;
}
if(CHINAchk.isChecked()){
count++;
}
if(SINGchk.isChecked()){
count++;
}
if(THAIchk.isChecked()){
count++;
}
if(INDIAchk.isChecked()){
count++;
}
return count;
}
}
public class CurrencyRate {
private String mcurrencyCode;
private double mresultValue;
private String conversionDescription;
public CurrencyRate(String mcurrencyCode, Double mresultValue, String conversionDescription) {
this.mcurrencyCode = mcurrencyCode;
this.mresultValue = mresultValue;
this.conversionDescription = conversionDescription;
}
public String getMcurrencyCode() {
return mcurrencyCode;
}
public double getMresultValue() {
return mresultValue;
}
public String getConversionDescription() {
return conversionDescription;
}
}
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collection;
public class CurrencyRateAdapter extends ArrayAdapter<CurrencyRate> {
MainActivity activity;
public CurrencyRateAdapter(Context context, ArrayList<CurrencyRate> resultRows){
super(context,0,resultRows);
activity=(MainActivity)activity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
try {
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
CurrencyRate currentCurrencyRate = getItem(position);
TextView currencyCodeTextView = (TextView) listItemView.findViewById(R.id.currency_code);
currencyCodeTextView.setText(currentCurrencyRate.getMcurrencyCode());
currencyCodeTextView.setTextColor(Color.parseColor("#FF0000"));
String currencyCode = currencyCodeTextView.toString();
TextView convDesTextView = (TextView) listItemView.findViewById(R.id.conversion_description);
convDesTextView.setText(currentCurrencyRate.getConversionDescription());
TextView resultValueTextView = (TextView) listItemView.findViewById(R.id.result_value);
Double result = currentCurrencyRate.getMresultValue();
int amount= activity.getAmount();
switch (currencyCode) {
case "USD":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "GBP":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "AUS":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "JPY":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "CNY":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "SGD":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "THB":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "INR":
result = amount * currentCurrencyRate.getMresultValue();
break;
default:
break;
}
String resultV = String.valueOf(result);
resultValueTextView.setText(resultV);
} catch (Exception e) {
Log.e("APP_TAG", "STACKTRACE");
Log.e("APP_TAG", Log.getStackTraceString(e));
}
return listItemView;
}
}
CurrencyRateAdapter.java
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
CheckBox USchk, UKchk, AUSchk, JAPchk, CHINAchk, SINGchk, THAIchk, INDIAchk;
EditText inputAmount;
Button convertButton;
int count = 0, checkedBoxes = 0;
TextView MYR;
CheckBox[] checkBoxArray;
ArrayList<CurrencyRate> currencyRates;
CurrencyRateAdapter currencyRateAdapter;
ArrayList<CurrencyRate> resultRows;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
inputAmount.setEnabled(false);
checkBoxArray = new CheckBox[]{
(CheckBox)findViewById(R.id.chkUS),
(CheckBox)findViewById(R.id.chkUK),
(CheckBox)findViewById(R.id.chkAUS),
(CheckBox)findViewById(R.id.chkJAP),
(CheckBox)findViewById(R.id.chkCHINA),
(CheckBox)findViewById(R.id.chkSING),
(CheckBox)findViewById(R.id.chkTHAI),
(CheckBox)findViewById(R.id.chkINDIA)
};
for (CheckBox cb: checkBoxArray) {
cb.setOnCheckedChangeListener(cbListener);
}
currencyRates = new ArrayList<CurrencyRate>();
currencyRates.add(new CurrencyRate("USD",4.25,"1 USD = 4.25 MYR"));
currencyRates.add(new CurrencyRate("GBP",5.60,"1 GBP = 5.60 MYR"));
currencyRates.add(new CurrencyRate("AUS",3.30,"1 AUD = 3.30 MYR"));
currencyRates.add(new CurrencyRate("JPY",0.0394,"1 JYP = 0.0394 MYR"));
currencyRates.add(new CurrencyRate("CNY",0.633,"1 CNY = 0.633 MYR"));
currencyRates.add(new CurrencyRate("SGD",3.10,"1 SGD = 3.10 MYR"));
currencyRates.add(new CurrencyRate("THB",0.128,"1 THB = 0.128 MYR"));
currencyRates.add(new CurrencyRate("INR",0.067,"1 INR = 0.067 MYR"));
resultRows = new ArrayList<CurrencyRate>();
//invokeAdapter();
//DECLARE ADAPTER
currencyRateAdapter = new CurrencyRateAdapter(this, resultRows);
ListView listView = (ListView) findViewById(resultListView);
listView.setAdapter(currencyRateAdapter);
}
private View.OnClickListener convertListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
checkedBoxes = countCheckboxes();
Toast.makeText(getApplicationContext(),"CLICKED CONVERT",Toast.LENGTH_SHORT).show();
int crBeforeCalc = currencyRates.size();
String crStrBCalc = Integer.toString(crBeforeCalc);
Log.i("crStrBCalc",crStrBCalc);
resultRows.clear();
//Execute Calculate function
calculateTotal(inputAmount,checkBoxArray,currencyRates);
int crAfterCalc = currencyRates.size();
String crStrACalc = Integer.toString(crAfterCalc);
Log.i("crStrACalc",crStrACalc);
}
};
//Calculate rates
private void calculateTotal(EditText inputAmount,CheckBox checkBoxArray[], ArrayList<CurrencyRate> currencyRates)
{
for(int i = 0; i < 8; i++) {
Log.i("THISTAG", "PRINT TIMES PRINTED LOOP");
if(checkBoxArray[i].isChecked())
{
Log.i("ifRuns","ifRuns");
resultRows.add(currencyRates.get(i));
}
}
//currencyRateAdapter.addAll(resultRows);
int rrDSize = resultRows.size();
String rrDStringSize = Integer.toString(rrDSize);
Log.i("rrDStringSize",rrDStringSize);
//currencyRateAdapter.notifyDataSetChanged();
int rrASize = resultRows.size();
String rrAStringSize = Integer.toString(rrASize);
Log.i("rrAStringSize",rrAStringSize);
}
public void initUI() {
USchk = (CheckBox) findViewById(R.id.chkUS);
UKchk = (CheckBox) findViewById(R.id.chkUK);
AUSchk = (CheckBox) findViewById(R.id.chkAUS);
JAPchk = (CheckBox) findViewById(R.id.chkJAP);
CHINAchk = (CheckBox) findViewById(R.id.chkCHINA);
SINGchk = (CheckBox) findViewById(R.id.chkSING);
THAIchk = (CheckBox) findViewById(R.id.chkTHAI);
INDIAchk = (CheckBox) findViewById(R.id.chkINDIA);
MYR = (TextView) findViewById(R.id.MYR);
convertButton = (Button) findViewById(R.id.convertButton);
inputAmount = (EditText) findViewById(R.id.amountInput);
convertButton.setOnClickListener(convertListener);
}
CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
disableChkWhenMax(checkBoxArray);
inputAmount.setText("");
//Clear all textbox rows
resultRows.clear();
}
};
private void disableChkWhenMax(CheckBox checkBoxes[]){
int countChecked =0;
inputAmount.setEnabled(false);
for (CheckBox cb:checkBoxes){
cb.setEnabled(true);
if (cb.isChecked()) countChecked++;
}
if(1<= countChecked)
{
inputAmount.setEnabled(true);
}
if (3 <= countChecked) {
for (CheckBox cb:checkBoxes){
if (!cb.isChecked())cb.setEnabled(false);
}
}
}
public int getAmount() {
int value=0;
if (inputAmount != null) {
return Integer.parseInt(inputAmount.getText().toString().trim());
} else {
return 0;
}
}
private int countCheckboxes()
{
if (USchk.isChecked()) {
count++;
}
if (UKchk.isChecked()){
count++;
}
if (AUSchk.isChecked()){
count++;
}
if(JAPchk.isChecked()){
count++;
}
if(CHINAchk.isChecked()){
count++;
}
if(SINGchk.isChecked()){
count++;
}
if(THAIchk.isChecked()){
count++;
}
if(INDIAchk.isChecked()){
count++;
}
return count;
}
}
public class CurrencyRate {
private String mcurrencyCode;
private double mresultValue;
private String conversionDescription;
public CurrencyRate(String mcurrencyCode, Double mresultValue, String conversionDescription) {
this.mcurrencyCode = mcurrencyCode;
this.mresultValue = mresultValue;
this.conversionDescription = conversionDescription;
}
public String getMcurrencyCode() {
return mcurrencyCode;
}
public double getMresultValue() {
return mresultValue;
}
public String getConversionDescription() {
return conversionDescription;
}
}
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collection;
public class CurrencyRateAdapter extends ArrayAdapter<CurrencyRate> {
MainActivity activity;
public CurrencyRateAdapter(Context context, ArrayList<CurrencyRate> resultRows){
super(context,0,resultRows);
activity=(MainActivity)activity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
try {
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
CurrencyRate currentCurrencyRate = getItem(position);
TextView currencyCodeTextView = (TextView) listItemView.findViewById(R.id.currency_code);
currencyCodeTextView.setText(currentCurrencyRate.getMcurrencyCode());
currencyCodeTextView.setTextColor(Color.parseColor("#FF0000"));
String currencyCode = currencyCodeTextView.toString();
TextView convDesTextView = (TextView) listItemView.findViewById(R.id.conversion_description);
convDesTextView.setText(currentCurrencyRate.getConversionDescription());
TextView resultValueTextView = (TextView) listItemView.findViewById(R.id.result_value);
Double result = currentCurrencyRate.getMresultValue();
int amount= activity.getAmount();
switch (currencyCode) {
case "USD":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "GBP":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "AUS":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "JPY":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "CNY":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "SGD":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "THB":
result = amount * currentCurrencyRate.getMresultValue();
break;
case "INR":
result = amount * currentCurrencyRate.getMresultValue();
break;
default:
break;
}
String resultV = String.valueOf(result);
resultValueTextView.setText(resultV);
} catch (Exception e) {
Log.e("APP_TAG", "STACKTRACE");
Log.e("APP_TAG", Log.getStackTraceString(e));
}
return listItemView;
}
}
不要在适配器中再次膨胀活动xml。这不是访问editText的正确方法 删除这些代码行
LayoutInflater inflater = LayoutInflater
.from(parent.getContext());
View view = inflater.inflate(R.layout.activity_main,null);
EditText inputAmount = (EditText)view.findViewById(R.id.amountInput);
String amountString = inputAmount.toString();
int i = Integer.parseInt(amountString);
而是创建一个方法来获取activity类中editText的值
public int getAmount() {
if (inputAmount != null) {
return Integer.parseInt(inputAmount.getText().toString().trim());
} else {
return 0;
}
}
并在适配器中传递活动引用
MainActivity activity;
//Constructor
public CurrencyRateAdapter(Context context, ArrayList<CurrencyRate> resultRows){
super(context,0,resultRows);
activity=(MainActivity)activity;
}
不要在适配器中再次膨胀活动xml。这不是访问editText的正确方法 删除这些代码行
LayoutInflater inflater = LayoutInflater
.from(parent.getContext());
View view = inflater.inflate(R.layout.activity_main,null);
EditText inputAmount = (EditText)view.findViewById(R.id.amountInput);
String amountString = inputAmount.toString();
int i = Integer.parseInt(amountString);
而是创建一个方法来获取activity类中editText的值
public int getAmount() {
if (inputAmount != null) {
return Integer.parseInt(inputAmount.getText().toString().trim());
} else {
return 0;
}
}
并在适配器中传递活动引用
MainActivity activity;
//Constructor
public CurrencyRateAdapter(Context context, ArrayList<CurrencyRate> resultRows){
super(context,0,resultRows);
activity=(MainActivity)activity;
}
换行
String resultV = String.valueOf(result);
换行
String resultV = String.valueOf(result);
发布异常堆栈跟踪。@LeoAso已经这样做了,谢谢。正如我所说,您的editText中没有任何值。发布异常堆栈跟踪。@LeoAso已经这样做了,谢谢。正如我所说,您的editText中没有任何值谢谢您的帮助!我收到以下错误:java.lang.NullPointerException:尝试在com.example.user.assignment2task3_v2.MainActivity.getAmount()上对com.example.user.assignment2task3_v2.CurrencyRateAdapter.getView上的空对象引用调用虚拟方法'int com.example.user.assignment2task3_v2'(CurrencyRateAdapter.java:87)确保inputAmount不为null并且它有内容,您正在向edittext添加值否?现在获取此信息:-错误:(59,37)错误:非静态方法getAmount()无法从静态上下文引用。这是否意味着将方法声明为静态?除非需要,否则不要将任何内容写入静态。将上下文保持为静态有时会导致内存泄漏。因此,将上下文设置为非静态,问题就解决了:)更改了“int amount=mainActivity.getAmount();”至“int amount=activity.getAmount();”它运行时没有崩溃,但是没有显示结果。谢谢你的帮助!我收到以下错误:java.lang.NullPointerException:尝试在com.example.user.assignment2task3_v2.MainActivity.getAmount()上对com.example.user.assignment2task3_v2.CurrencyRateAdapter.getView上的空对象引用调用虚拟方法'int com.example.user.assignment2task3_v2'(CurrencyRateAdapter.java:87)确保inputAmount不为null并且它有内容,您正在向edittext添加值否?现在获取此信息:-错误:(59,37)错误:非静态方法getAmount()无法从静态上下文引用。这是否意味着将方法声明为静态?除非需要,否则不要将任何内容写入静态。将上下文保持为静态有时会导致内存泄漏。因此,将上下文设置为非静态,问题就解决了:)更改了“int amount=mainActivity.getAmount();”至“int amount=activity.getAmount();”它运行时没有崩溃,但没有显示任何结果。您好,您已经这样做了,但我收到了错误:NullPointerException:尝试对空对象引用调用虚拟方法“int com.example.user.assignment2task3_v2.MainActivity.getAmount()”,您好,已执行此操作,但我收到错误:NullPointerException:尝试对null对象引用调用虚拟方法“int com.example.user.assignment2task3_v2.MainActivity.getAmount()”