gpt4 book ai didi

java - 从适配器类获取不同 Activity 中的 EditText 值

转载 作者:行者123 更新时间:2023-12-01 20:12:46 27 4
gpt4 key购买 nike

我对 Android 相当陌生,我正在尝试构建一个货币转换器应用程序。我无法理解如何从CurrencyRateAdapter.java 内部访问activity_main.xml 中的EditText。我尝试过膨胀 View - 代码构建时没有错误,但在选择复选框、输入值然后按转换后崩溃。

编辑

更改了“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;
}

}

CurrencyRate.java

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


}

CurrencyRateAdapter.java

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;

}

}

listItem.xml

<?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="wrap_content"
android:paddingLeft="16dp">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">

<TextView
android:id="@+id/currency_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:textStyle="bold"
android:textSize="30sp"/>

<TextView
android:id="@+id/result_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="30sp" />

</LinearLayout>

<TextView
android:id="@+id/conversion_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />


</LinearLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="30dp"
android:paddingTop="30dp">

<TextView
android:id="@+id/selectCurrency"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/question1"
android:textSize="20sp"
android:textColor="#000000"
android:layout_alignParentTop="true" />

<!--ROW 1 - US, UK, AUS, JAP-->
<CheckBox
android:id="@+id/chkUS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/selectCurrency"
android:layout_marginTop="32dp" />

<ImageView
android:id="@+id/imgUS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/united_states"
android:layout_toRightOf="@id/chkUS"
android:layout_alignBottom="@id/chkUS" />

<CheckBox
android:id="@+id/chkUK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/imgUS"
android:layout_alignBottom="@id/chkUS"/>

<ImageView
android:id="@+id/imgUK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/united_kingdom"
android:layout_toRightOf="@id/chkUK"
android:layout_alignBottom="@id/chkUK" />

<CheckBox
android:id="@+id/chkAUS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/imgUK"
android:layout_alignBottom="@id/chkUK"/>

<ImageView
android:id="@+id/imgAUS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/australia"
android:layout_toRightOf="@id/chkAUS"
android:layout_alignBottom="@id/chkAUS" />

<CheckBox
android:id="@+id/chkJAP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/imgAUS"
android:layout_alignBottom="@id/chkAUS"/>

<ImageView
android:id="@+id/imgJAP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/japan"
android:layout_toRightOf="@id/chkJAP"
android:layout_alignBottom="@id/chkJAP" />

<!--ROW 2 - CHINA, SING, THAI, INDIA-->
<CheckBox
android:id="@+id/chkCHINA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/chkUS"
android:layout_marginTop="32dp" />

<ImageView
android:id="@+id/imgCHINA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/china"
android:layout_toRightOf="@id/chkCHINA"
android:layout_alignBottom="@id/chkCHINA" />

<CheckBox
android:id="@+id/chkSING"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/imgCHINA"
android:layout_alignBottom="@id/chkCHINA"/>

<ImageView
android:id="@+id/imgSING"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/singapore"
android:layout_toRightOf="@id/chkSING"
android:layout_alignBottom="@id/chkSING" />

<CheckBox
android:id="@+id/chkTHAI"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/imgSING"
android:layout_alignBottom="@id/chkSING"/>

<ImageView
android:id="@+id/imgTHAI"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/thailand"
android:layout_toRightOf="@id/chkTHAI"
android:layout_alignBottom="@id/chkTHAI" />

<CheckBox
android:id="@+id/chkINDIA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/imgTHAI"
android:layout_alignBottom="@id/chkTHAI"/>

<ImageView
android:id="@+id/imgINDIA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/india"
android:layout_toRightOf="@id/chkINDIA"
android:layout_alignBottom="@id/chkINDIA" />

<View
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_width="330dp"
android:layout_height="3dp"
android:layout_below="@id/imgINDIA"
android:background="#ff0000" />

<TextView
android:id="@+id/enterAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/question2"
android:textSize="20sp"
android:textColor="#000000"
android:layout_below="@id/imgCHINA"
android:paddingTop="30dp"/>

<TextView
android:id="@+id/MYR"
android:text="MYR"
android:textColor="@color/colorPrimaryDark"
android:textStyle="bold"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="15dp"
android:paddingTop="15dp"
android:layout_below="@id/enterAmount"/>

<EditText
android:id="@+id/amountInput"
android:textSize="20sp"
android:inputType="numberSigned"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/MYR"
android:layout_below="@id/enterAmount"
android:paddingTop="15dp"
android:paddingRight="150dp"
android:paddingBottom="10dp"/>

<Button
android:id="@+id/convertButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CONVERT"
android:layout_toRightOf="@id/amountInput"
android:layout_below="@id/enterAmount"/>

<TextView
android:id="@+id/eqCurrency"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/question3"
android:textSize="20sp"
android:textColor="#000000"
android:paddingTop="15dp"
android:layout_below="@id/amountInput" />

<ListView
android:id="@+id/resultListView"
android:layout_below="@id/eqCurrency"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

</RelativeLayout>

堆栈跟踪

09-26 13:54:45.626 5735-5735/com.example.user.assignment2task3_v2 E/APP_TAG: STACKTRACE
09-26 13:54:45.627 5735-5735/com.example.user.assignment2task3_v2 E/APP_TAG: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.example.user.assignment2task3_v2.MainActivity.getAmount()' on a null object reference
at com.example.user.assignment2task3_v2.CurrencyRateAdapter.getView(CurrencyRateAdapter.java:53)
at android.widget.AbsListView.obtainView(AbsListView.java:2363)
at android.widget.ListView.makeAndAddView(ListView.java:1970)
at android.widget.ListView.fillDown(ListView.java:704)
at android.widget.ListView.fillFromTop(ListView.java:765)
at android.widget.ListView.layoutChildren(ListView.java:1744)
at android.widget.AbsListView.onLayout(AbsListView.java:2162)
at android.view.View.layout(View.java:17637)
at android.view.ViewGroup.layout(ViewGroup.java:5575)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
at android.view.View.layout(View.java:17637)
at android.view.ViewGroup.layout(ViewGroup.java:5575)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:17637)
at android.view.ViewGroup.layout(ViewGroup.java:5575)
at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437)
at android.view.View.layout(View.java:17637)
at android.view.ViewGroup.layout(ViewGroup.java:5575)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:17637)
at android.view.ViewGroup.layout(ViewGroup.java:5575)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1741)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
at android.view.View.layout(View.java:17637)
at android.view.ViewGroup.layout(ViewGroup.java:5575)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:726)
at android.view.View.layout(View.java:17637)
at android.view.ViewGroup.layout(ViewGroup.java:5575)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2346)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2068)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6337)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
at android.view.Choreographer.doCallbacks(Choreographer.java:686)
at android.view.Choreographer.doFrame(Choreographer.java:621)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

最佳答案

不要在适配器中再次膨胀 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;
}
}

并在您的适配器中传递 Activity 引用。

MainActivity activity;

//Constructor
public CurrencyRateAdapter(Context context, ArrayList<CurrencyRate> resultRows){
super(context,0,resultRows);
activity=(MainActivity)activity;
}

使用这样的 Activity 引用访问方法

int amount= activity.getAmount();

关于java - 从适配器类获取不同 Activity 中的 EditText 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46426933/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com