Java 我想在调用Fragment方法的MainActivity中获取片段数据
我想在搜索城市名称库中显示当前天气数据的片段。意思是说,如果我在搜索框中输入任何城市名称,它会显示该城市的当前天气。如果我给出静态城市名称,所有的工作都正常进行,但我希望我选择的城市能给出当前的数据 搜索框(EditText)位于主活动和currentweather数据方法上,我想在其中显示我的currentweather数据片段。如何搜索主要活动并在片段布局中显示当前天气数据 主要活动Java 我想在调用Fragment方法的MainActivity中获取片段数据,java,android,android-fragments,Java,Android,Android Fragments,我想在搜索城市名称库中显示当前天气数据的片段。意思是说,如果我在搜索框中输入任何城市名称,它会显示该城市的当前天气。如果我给出静态城市名称,所有的工作都正常进行,但我希望我选择的城市能给出当前的数据 搜索框(EditText)位于主活动和currentweather数据方法上,我想在其中显示我的currentweather数据片段。如何搜索主要活动并在片段布局中显示当前天气数据 主要活动 package com.deitel.apiretrofitfragmentweatherapp;
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.text.TextUtils;
import android.util.Log;
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.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";
/* public static String lat = "33.69";
public static String lon = "73.06";*/
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 currentweather currentweather = new currentweather();
btn_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager manager=getSupportFragmentManager();
currentweather weather= (currentweather) manager.findFragmentById(R.id.current_weather);
assert weather != null;
weather.getCurrentData();
String City= text_search.getText().toString().trim();
Bundle bundle = new Bundle();
bundle.putString("search_city", City);
currentweather.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.fragment_container, currentweather).commit();
currentweather.getCurrentData();
if (TextUtils.isEmpty(City)) {
text_search.setError("Enter City Name");
return;
}
}
});
fragementViewAdapter = new FragementViewAdapter(getSupportFragmentManager());
viewPager.setAdapter(fragementViewAdapter);
tabLayout.setupWithViewPager(viewPager);
fragmentManager = getSupportFragmentManager();
}
}
当前天气片段
package com.deitel.apiretrofitfragmentweatherapp.Fragment;
import android.os.Bundle;
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 androidx.fragment.app.Fragment;
import com.deitel.apiretrofitfragmentweatherapp.CurrentWeather.WeatherResponse;
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);
/* Bundle bundle=getArguments();
if (bundle!=null)
{
city=bundle.getString("search_city");
textView_country.setText(city);
Log.d("ass",""+city);
}*/
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);
return itemview;
}
public void getCurrentData() {
String City1 = null;
if (getArguments() != null){
City1=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(City1, 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);
Toast.makeText(getContext(), "Successfully", Toast.LENGTH_SHORT).show();
}
if (response.code()==404)
{
Toast.makeText(getContext(), "City Not Founded", Toast.LENGTH_SHORT).show();
}
}
@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());
}
});
}
}
package com.deitel.apirfragmentWeatherApp.Fragment;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.TextView;
导入android.widget.Toast;
导入androidx.fragment.app.fragment;
导入com.deitel.apirgmentWeatherApp.CurrentWeather.WeatherResponse;
导入com.deitel.api.weatherapp.R;
导入com.deitel.apirationFragmentWeatherApp.Reformation.WeatherService;
导入java.text.simpleDataFormat;
导入java.util.Calendar;
2.电话;;
2.回拨;
2.回应;;
进口改装2.改装;
进口改装2.converter.gson.GsonConverterFactory;
导入静态com.deitel.apiFragmentWeatherApp.MainActivity.AppId;
导入静态com.deitel.apiFragmentWeatherApp.MainActivity.BaseUrl;
公共类currentweather扩展片段{
公共文本查看文本国家、文本城市、文本压力、文本湿度、文本温度;
公共文本视图文本视图国家/地区、文本视图城市、文本视图临时、,
text查看压力、text查看湿度、text查看日期;
/*公共文本视图文本视图*/
公共天气{
//必需的空公共构造函数
}
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
视图项视图=充气机。充气(R.layout.fragment\u currentweather,container,false);
textView\u country=itemview.findViewById(R.id.textView\u country);
textView\u city=itemview.findViewById(R.id.textView\u city);
textView\u temp=itemview.findViewById(R.id.textView\u temp);
textView\u pressure=itemview.findViewById(R.id.textView\u pressure);
textView\u湿度=itemview.findViewById(R.id.textView\u湿度);
textview\u date=itemview.findViewById(R.id.textview\u date);
text\u country=itemview.findviewbyd(R.id.text\u country);
text\u city=itemview.findviewbyd(R.id.text\u city);
/*text\u view=itemview.findviewbyd(R.id.text\u view)*/
text\u pressure=itemview.findviewbyd(R.id.text\u pressure);
text\u湿度=itemview.findviewbyd(R.id.text\u湿度);
text_temp=itemview.findviewbyd(R.id.text_temp);
/*Bundle=getArguments();
if(bundle!=null)
{
city=bundle.getString(“搜索城市”);
textView_country.setText(城市);
Log.d(“ass”和“+城市);
}*/
text_country.setVisibility(View.GONE);
text_city.setVisibility(View.GONE);
文本压力设置可见性(视图消失);
text_湿度设置可见性(View.GONE);
文本温度设置可见性(视图消失);
返回项目视图;
}
public void getCurrentData(){
字符串City1=null;
如果(getArguments()!=null){
City1=getArguments().getString(“搜索城市”);
}
改装改装=新改装.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherService WeatherService=改装.create(WeatherService.class);
Call Call=weatherService.getCurrentWeatherDataCityName(City1,AppId);
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
if(response.code()==200){
WeatherResponse=(WeatherResponse)response.body();
断言weatherResponse!=null;
日历=Calendar.getInstance();
SimpleDataFormat SimpleDataFormat=新SimpleDataFormat(“EEEE dd MM”);
String formattedate=simpleDateFormat.format(calendar.getTime());
/*String stringbuilder=“国家:”+
weatherResponse.sys.country+
“\n”+
城市:+weatherResponse.name+
“\n”+
“温度:”+weatherResponse.main.temp+
“\n”+
“温度(分钟):”+
weatherResponse.main.temp_min+
“\n”+
“温度(最大值):”+
weatherResponse.main.temp_max+
“\n”+
“湿度:”+
天气响应+
“\n”+
“压力:”+
天气响应、主压力*/
字符串Country=weatherResponse.sys.Country;
字符串City=weatherResponse.name;
字符串温度=字符串值(weatherResponse.main.Temp);
双钙=Double.parseDouble(温度)-273.0;
整数i=calcius.intValue();
管柱压力=管柱.valueOf(weatherResponse.main.Pressure);
字符串湿度=字符串.valueOf(weatherResponse.main.湿度);
textView_country.setText(Cou
<?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"
android:id="@+id/current_weather"
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="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
1-03 19:35:10.586 1428-1428/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.deitel.apiretrofitfragmentweatherapp, PID: 1428
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:107)
at android.widget.Toast.makeText(Toast.java:264)
at com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather$1.onResponse(currentweather.java:129)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
01-03 21:43:00.695 10885-10885/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.deitel.apiretrofitfragmentweatherapp, PID: 10885
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.deitel.apiretrofitfragmentweatherapp/com.deitel.apiretrofitfragmentweatherapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.getCurrentData()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.getCurrentData()' on a null object reference
at com.deitel.apiretrofitfragmentweatherapp.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6301)