简体   繁体   English

我想从 Activity 获取编辑文本数据并显示在 Fragment 中,但它给了我错误

[英]I want to get edit text data from Activity and and show in Fragment but it give me error

I want to get Edit Text data from activity and use it in fragment.我想从活动中获取编辑文本数据并在片段中使用它。 Basically in Fragment I show the current weather data with city name which I entered and I entered this Edit text data in Main Activity and pass this Edit Text data in fragment and set this string value in fragment.基本上在片段中,我用我输入的城市名称显示当前天气数据,然后在主活动中输入此编辑文本数据,并在片段中传递此编辑文本数据并在片段中设置此字符串值。

So I have these errors.所以我有这些错误。 I try a lot to solve it but I can not resolve it.我尝试了很多来解决它,但我无法解决它。

MainActivity.Class主Activity.Class

package com.deitel.apiretrofitfragmentweatherapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.deitel.apiretrofitfragmentweatherapp.Adapter.FragementViewAdapter;
import com.deitel.apiretrofitfragmentweatherapp.Fragment.ForcastWeather;
import com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather;
import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {
    private  static FragmentManager fragmentManager;
    public static String BaseUrl = "http://api.openweathermap.org/";
    public static String AppId = "08fd7374790f2ccee9f1f1dbfae38fdf";
    ViewPager viewPager;
    FragementViewAdapter fragementViewAdapter;
    TabLayout tabLayout;
    EditText text_search;
    ImageButton btn_search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager=getSupportFragmentManager();
        text_search = findViewById(R.id.text_search_city);
        tabLayout = findViewById(R.id.tab_layout);
        viewPager = findViewById(R.id.fragment_container);
        btn_search = findViewById(R.id.btn_search);
        final String City = text_search.getText().toString().trim();
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("search_city",City);
                currentweather currentweather = new currentweather();
                currentweather.setArguments(bundle);
                fragmentManager.beginTransaction().replace(R.id.fragment_container,currentweather).commit();
                Toast.makeText(MainActivity.this, "successfully", Toast.LENGTH_SHORT).show();
            }
        });
        fragementViewAdapter = new FragementViewAdapter(getSupportFragmentManager());
        viewPager.setAdapter(fragementViewAdapter);
        tabLayout.setupWithViewPager(viewPager);
        fragmentManager=getSupportFragmentManager();
  }
}

CurrentWeatherFragment.Class CurrentWeatherFragment.Class

package com.deitel.apiretrofitfragmentweatherapp.Fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.deitel.apiretrofitfragmentweatherapp.CurrentWeather.WeatherResponse;
import com.deitel.apiretrofitfragmentweatherapp.ForecastWeather.City;
import com.deitel.apiretrofitfragmentweatherapp.R;
import com.deitel.apiretrofitfragmentweatherapp.Retrofit.WeatherService;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.deitel.apiretrofitfragmentweatherapp.MainActivity.AppId;
import static com.deitel.apiretrofitfragmentweatherapp.MainActivity.BaseUrl;

public class currentweather extends Fragment {
    public TextView text_country,text_city,text_pressure,text_humidity,text_temp;
    public TextView textView_country, textView_city, textView_temp,
            textView_pressure, textView_humidity, textview_date;
    /*public TextView text_view;*/
    public currentweather() {
        // Required empty public constructor
    }
        @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View itemview=inflater.inflate(R.layout.fragment_currentweather, container, false);
            textView_country = itemview.findViewById(R.id.textView_country);
            textView_city =itemview.findViewById(R.id.textView_city);
            textView_temp =itemview.findViewById(R.id.textview_temp);
            textView_pressure =itemview.findViewById(R.id.textView_pressure);
            textView_humidity =itemview.findViewById(R.id.textView_humidity);
            textview_date =itemview.findViewById(R.id.textView_date);
            text_country= itemview.findViewById(R.id.text_country);
            text_city=itemview. findViewById(R.id.text_city);
            /*text_view=itemview.findViewById(R.id.text_view);*/
            text_pressure=itemview. findViewById(R.id.text_pressure);
            text_humidity=itemview.findViewById(R.id.text_humidity);
            text_temp=itemview.findViewById(R.id.text_temp);
            text_country.setVisibility(View.GONE);
            text_city.setVisibility(View.GONE);
            text_pressure.setVisibility(View.GONE);
            text_humidity.setVisibility(View.GONE);
            text_temp.setVisibility(View.GONE);
            getCurrentData();
            return itemview;
    }
    void getCurrentData() {
         String city=getArguments().getString("search_city");
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        WeatherService weatherService = retrofit.create(WeatherService.class);
        Call<WeatherResponse> call = weatherService.getCurrentWeatherDataCityName(city, AppId);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response.code() == 200) {
                    WeatherResponse weatherResponse = (WeatherResponse) response.body();
                    assert weatherResponse != null;
                    Calendar calendar = Calendar.getInstance();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE-dd-MM");
                    String formatedate = simpleDateFormat.format(calendar.getTime());
                   /* String stringbuilder= "Country : " +
                            weatherResponse.sys.country +
                            "\n" +
                            "City : " +weatherResponse.name +
                            "\n" +
                            "Tempreture : " + weatherResponse.main.temp +
                            "\n" +
                            "Tempreture(Min) : " +
                            weatherResponse.main.temp_min +
                            "\n" +
                            "Tempreture(Max) : " +
                            weatherResponse.main.temp_max +
                            "\n" +
                            "Humidity : " +
                            weatherResponse.main.humidity +
                            "\n" +
                            "Pressure : " +
                            weatherResponse.main.pressure;*/
                    String Country = weatherResponse.sys.country;
                    String City = weatherResponse.name;
                    String Temp = String.valueOf(weatherResponse.main.temp);
                    Double calcius = Double.parseDouble(Temp) - 273.0;
                    Integer i = calcius.intValue();
                    String Pressure = String.valueOf(weatherResponse.main.pressure);
                    String Humidity = String.valueOf(weatherResponse.main.humidity);
                    textView_country.setText(Country);
                    textView_city.setText(City);
                    textView_temp.setText(String.valueOf(i));
                    textView_pressure.setText(Pressure);
                    textView_humidity.setText(Humidity);
                    textview_date.setText(formatedate);
                    text_country.setVisibility(View.VISIBLE);
                    text_city.setVisibility(View.VISIBLE);
                    text_pressure.setVisibility(View.VISIBLE);
                    text_humidity.setVisibility(View.VISIBLE);
                    text_temp.setVisibility(View.VISIBLE);
                }
                if (response.code()==404)
                {
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                textView_country.setText(t.getMessage());
                textView_city.setText(t.getMessage());
                textView_temp.setText(t.getMessage());
                textView_pressure.setText(t.getMessage());
                textView_humidity.setText(t.getMessage());
                textview_date.setText(t.getMessage());
            }
        });
    }

}

CurrentWeatherFragment.XML当前天气片段.XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
                        <TextView
                android:id="@+id/text_country"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text="Country"
                android:textColor="#000"
                android:textSize="25dp"
                android:textStyle="bold"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView_date" />

            <TextView
                android:id="@+id/textView_country"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text=""
                android:textColor="#000"
                android:textSize="17dp"
                android:textStyle="bold"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/text_country" />

            <TextView
                android:id="@+id/text_city"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginEnd="10dp"
                android:layout_marginRight="10dp"
                android:text="City"
                android:textColor="#000"
                android:textSize="25dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView_date" />

            <TextView
                android:id="@+id/textView_city"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginEnd="10dp"
                android:layout_marginRight="10dp"
                android:text=""
                android:textColor="#000"
                android:textSize="17dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/text_city" />

            <TextView
                android:id="@+id/text_temp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="90dp"
                android:text="Temperature"
                android:textColor="#000"
                android:textSize="25dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="@+id/textView_country"
                app:layout_constraintTop_toBottomOf="@id/textView_date" />

            <TextView
                android:id="@+id/textview_temp"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginTop="40dp"
                android:gravity="center"
                android:text=""
                android:textColor="#000"
                android:textSize="40dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="@+id/text_temp" />

            <TextView
                android:id="@+id/text_pressure"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Pressure"
                android:textColor="#000"
                android:textSize="25dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textview_temp" />

            <TextView
                android:id="@+id/textView_pressure"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text=""
                android:textColor="#000"
                android:textSize="17dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/text_pressure" />

            <TextView
                android:id="@+id/text_humidity"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="Humidity"
                android:textColor="#000"
                android:textSize="25dp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView_pressure" />

            <TextView
                android:id="@+id/textView_humidity"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="32dp"
                android:layout_marginBottom="32dp"
                android:text=""
                android:textColor="#000"
                android:textSize="17dp"
                android:textStyle="bold"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/text_humidity" />-->

            <TextView
                android:id="@+id/textView_date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:text=""
                android:textColor="#000"
                android:textSize="17dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parentpa" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

Errors:错误:

    01-03 15:16:31.862 15251-15251/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.deitel.apiretrofitfragmentweatherapp, PID: 15251
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on
a null object reference
        at com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.getCurrentData(currentweather.java:69)
        at com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.onCreateView(currentweather.java:64)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execSingleAction(FragmentManagerImpl.java:1696)
        at androidx.fragment.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:299)
        at androidx.fragment.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:235)

As I understand from your question, You have one Activity class and a fragment is inside that activity.正如我从您的问题中了解到的,您有一个 Activity 类,并且该活动中包含一个片段。 You have one edit text for search in your activity class and When you enter something in your activity's search box you want that result in your fragment class.您有一个用于在您的活动类中搜索的编辑文本,并且当您在活动的搜索框中输入内容时,您希望该结果出现在您的片段类中。 If I understood your requirement then you should change a bit your current implementation.如果我理解你的要求,那么你应该稍微改变一下你当前的实现。

  1. Create a class level (Global) fragment instance.创建一个类级别(全局)片段实例。
  2. Create one method with string input parameter (eg. searchWeather(String searchedText)) in fragment and make it public.在片段中创建一个带有字符串输入参数的方法(例如 searchWeather(String searchedText))并将其公开。
  3. After Text input completed you just call fragment's method from activity class as we have a present current object of that fragment in screen(ex. currentweather.searchWeather("test") )文本输入完成后,您只需从活动类中调用片段的方法,因为我们在屏幕中有该片段的当前对象(例如 currentweather.searchWeather("test") )
  4. Now you might get that last entered text in your fragment.现在您可能会在片段中获得最后输入的文本。

This way you can manage communication between activity and fragment.通过这种方式,您可以管理活动和片段之间的通信。

Please feel free to ask, If you have any further issues/questions in implementation.如果您在实施过程中有任何其他问题/疑问,请随时提问。

Example :例子 :

Activity class:活动类:

public class MainActivity extends Activity {

CurrentWeatherFragment currentWeatherFragment;
EditText searchText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    searchText = new EditText(this);

    currentWeatherFragment = new CurrentWeatherFragment();
    getFragmentManager().beginTransaction().replace(R.id.fragment_container,currentWeatherFragment).commit();

    searchText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                 if (currentWeatherFragment != null){
                     currentWeatherFragment.searchWeather(charSequence.toString());
                 }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

}
}

Fragment class:片段类:

public class CurrentWeatherFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return super.onCreateView(inflater, container, savedInstanceState);
}

public void searchWeather(String searchedText){
    //Do your work here
    }
}

I see that you need the city name which you enter in your MainActivity when you make Retrofit call to fetch the weather data from your fragment class.我看到当您进行 Retrofit 调用以从片段类中获取天气数据时,您需要在 MainActivity 中输入的城市名称。 So your city data should not be empty or null.因此,您的城市数据不应为空或为空。

I see that you are getting the text using the line final String City = text_search.getText().toString().trim();我看到您使用final String City = text_search.getText().toString().trim();行获取文本final String City = text_search.getText().toString().trim(); in your MainActivity.在您的 MainActivity 中。 Kindly put that line onside the click listener of button like below请将该行放在按钮的单击侦听器上,如下所示

 btn_search.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String City = text_search.getText().toString().trim();
            Bundle bundle = new Bundle();
            bundle.putString("search_city",City);
            currentweather currentweather = new currentweather();
            currentweather.setArguments(bundle);
            fragmentManager.beginTransaction().replace(R.id.fragment_container,currentweather).commit();
            Toast.makeText(MainActivity.this, "successfully", Toast.LENGTH_SHORT).show();
        }
    });

This will get the text from the edittext whenever you click on search button and you will not receive the null exception.每当您单击搜索按钮时,这都会从编辑文本中获取文本,并且您不会收到空异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android 将 Edit Text 数据 onChange 从 Activity 传递到 Fragment - Android pass Edit Text data onChange from Activity to Fragment 这个androied项目给我一个崩溃,我正在尝试使项目具有“编辑文本”中的一个数字,并在文本视图中获得两倍 - this androied project give me a crash i am trying to make project that have a number from Edit text and get it in a text view times two 我想从片段开始活动,但它崩溃了 - I want to start activity from fragment but It get crashed 将编辑文本值从片段传递到活动 - Pass edit text value from Fragment to Activity 我想将数据从活动转移到片段,然后在片段中显示数据。 我的代码不起作用 - I want to transfer data from activity to fragment and then display data in the fragment. My code doesn't work 从编辑文本获取文本到另一个活动 - Get text from edit text to another activity 我想使用回收者视图将数据从Firebase获取到内部片段 - I want to get data from firebase to inside fragment with recycler view 我想从 Realm 数据库中删除数据,但它给了我错误 - I want to delete data from Realm database, but it gives me error 从EditText从片段到活动获取数据 - Get data from EditText from Fragment to Activity Android Studio:如何从活动获取用户输入(从微调器和编辑文本)到另一个活动? - Android Studio: How do I get user input (From Spinner and Edit Text) from activity to another activity?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM