从适配器类获取不同活动中的 EditText 值

Posted

技术标签:

【中文标题】从适配器类获取不同活动中的 EditText 值【英文标题】:Getting EditText value in different activity from adapter class 【发布时间】:2017-09-26 12:44:02 【问题描述】:

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

编辑

改变了'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_
    android:layout_
    android:paddingLeft="16dp">

    <LinearLayout
        android:layout_
        android:layout_
        android:orientation="horizontal">

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

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

    </LinearLayout>

    <TextView
        android:id="@+id/conversion_description"
        android:layout_
        android:layout_
        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_
    android:layout_
    android:paddingLeft="30dp"
    android:paddingTop="30dp">

    <TextView
        android:id="@+id/selectCurrency"
        android:layout_
        android:layout_
        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_
        android:layout_
        android:layout_below="@id/selectCurrency"
        android:layout_marginTop="32dp" />

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

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

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

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

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

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

    <ImageView
        android:id="@+id/imgJAP"
        android:layout_
        android:layout_
        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_
        android:layout_
        android:layout_below="@id/chkUS"
        android:layout_marginTop="32dp" />

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

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

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

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

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

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

    <ImageView
        android:id="@+id/imgINDIA"
        android:layout_
        android:layout_
        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_
        android:layout_
        android:layout_below="@id/imgINDIA"
        android:background="#ff0000" />

    <TextView
        android:id="@+id/enterAmount"
        android:layout_
        android:layout_
        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_
        android:layout_
        android:paddingRight="15dp"
        android:paddingTop="15dp"
        android:layout_below="@id/enterAmount"/>

    <EditText
        android:id="@+id/amountInput"
        android:textSize="20sp"
        android:inputType="numberSigned"
        android:layout_
        android:layout_
        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_
        android:layout_
        android:text="CONVERT"
        android:layout_toRightOf="@id/amountInput"
        android:layout_below="@id/enterAmount"/>

    <TextView
        android:id="@+id/eqCurrency"
        android:layout_
        android:layout_
        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_
        android:layout_ />

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

【问题讨论】:

发布异常堆栈跟踪。 @LeoAso 已经这样做了,谢谢。 正如我所说,您的 editText 没有任何价值 【参考方案1】:

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

像这样使用活动引用访问方法

int amount= activity.getAmount();

【讨论】:

感谢您的帮助!我收到以下错误:java.lang.NullPointerException: Attempt to invoke virtual method 'int com.example.user.assignment2task3_v2.MainActivity.getAmount()' on an null object reference at com.example.user.assignment2task3_v2.CurrencyRateAdapter .getView(CurrencyRateAdapter.java:87) 确保 inputAmount 不为 null 并且它有内容,您正在为该 edittext 添加值吗? 立即获取:----Error:(59, 37) 错误:无法从静态上下文引用非静态方法 getAmount()。这是否意味着将方法声明为静态? 除非你需要它,否则不要写任何静态的东西。保持上下文为静态有时会导致内存泄漏。所以将你的上下文设置为非静态,问题就解决了:) 改变了'int amount= mainActivity.getAmount();'到 'int amount=activity.getAmount();'它运行没有崩溃,但没有显示结果。【参考方案2】:

更改以下行

  String resultV = String.valueOf(result);

【讨论】:

您好,已经这样做了,但出现错误:NullPointerException: Attempt to invoke virtual method 'int com.example.user.assignment2task3_v2.MainActivity.getAmount()' on an null object reference

以上是关于从适配器类获取不同活动中的 EditText 值的主要内容,如果未能解决你的问题,请参考以下文章

如何从另一个模型中获取 EditText 的值/制作一个 o

使用kotlin从android中的BroadcastReceiver类访问edittext

无法从 Listview 的 EditText 中获取值?

如何从一个活动中获取edittext值到下一个活动的recyclerview?

如何从另一个活动中编辑和获取 editText 输入字段的更新?

如何在自定义 ListView 中获取 EditText 的所有值