[英]My findViewByid turn red on extend fragment, im doing on onCreate method not in onCreateView method
通過標識為紅色的id查找視圖,我不是要對onCreateView執行此操作,請幫助我解決此類錯誤,我真的是android編程的新手
package com.example.mymonitoring;
public class MonitoringFragment extends Fragment {
private static final String TAG = "STATISTICACTIVITY";
private Button Temperature;
private Button Humidity;
private TextView t1;
private TextView t2;
private static TextView t3;
private static final String THINGSPEAK_CHANNEL_ID = "572138";
private static final String THINGSPEAK_API_KEY = "ND76MAN2CWQJG25G"; //GARBAGE KEY
private static final String THINGSPEAK_API_KEY_STRING = "ND76MAN2CWQJG25G";
/* Be sure to use the correct fields for your own app*/
private static final String THINGSPEAK_FIELD1 = "field1";
private static final String THINGSPEAK_FIELD2 = "field2";
private static final String THINGSPEAK_FIELD3 = "field3";
private static final String THINGSPEAK_UPDATE_URL = "https://api.thingspeak.com/update?";
private static final String THINGSPEAK_CHANNEL_URL = "https://api.thingspeak.com/channels/";
private static final String THINGSPEAK_FEEDS_LAST = "/feeds/last?";
private ThingSpeakChannel tsChannel;
private ThingSpeakLineChart tsChart;
private LineChartView chartView;
public MonitoringFragment() {
// Required empty public constructor
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return v;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
t1 = (TextView) findViewById(R.id.tempNumber);
t2 = (TextView) findViewById(R.id.humidNumber);
ThingSpeakChannel tsChannel = new ThingSpeakChannel(572138);
tsChannel.setChannelFeedUpdateListener(new ThingSpeakChannel.ChannelFeedUpdateListener() {
@Override
public void onChannelFeedUpdated(long channelId, String channelName, ChannelFeed channelFeed) {
// Make use of your Channel feed here!
// Show Channel ID and name on the Action Bar
//getSupportActionBar().setTitle(channelName);
// Notify last update time of the Channel feed through a Toast message
Date lastUpdate = channelFeed.getChannel().getUpdatedAt();
//Toast.makeText(MonitoringFragment.this, lastUpdate.toString(), Toast.LENGTH_SHORT).show();
}
});
tsChannel.loadChannelFeed();
Temperature = (Button) findViewById(R.id.btnTemperature);
Humidity = (Button) findViewById(R.id.btnHumidity);
Temperature.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
findViewById(R.id.TemperatureLayout).setVisibility(View.VISIBLE);
findViewById(R.id.HumidityLayout).setVisibility(View.GONE);
final LineChartView chartView = (LineChartView) findViewById(R.id.TempChart);
tsChart = new ThingSpeakLineChart(572138, 1);
tsChart.setListener(new ThingSpeakLineChart.ChartDataUpdateListener() {
@Override
public void onChartDataUpdated(long channelId, int fieldId, String title, LineChartData lineChartData, Viewport maxViewport, Viewport initialViewport) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, -5);
tsChart.setNumberOfEntries(200);
// Set value axis labels on 10-unit interval
tsChart.setValueAxisLabelInterval(10);
// Set date axis labels on 5-minute interval
tsChart.setDateAxisLabelInterval(1);
// Show the line as a cubic spline
tsChart.useSpline(true);
// Set the line color
tsChart.setLineColor(Color.parseColor("#D32F2F"));
// Set the axis color
tsChart.setAxisColor(Color.parseColor("#455a64"));
// Set the starting date (5 minutes ago) for the default viewport of the chart
tsChart.setChartStartDate(calendar.getTime());
chartView.setLineChartData(lineChartData);
chartView.setMaximumViewport(maxViewport);
chartView.setCurrentViewport(initialViewport);
}
});
tsChart.loadChartData();
try {
new FetchThingspeakTempTask().execute();
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
}
}
});
Humidity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
findViewById(R.id.HumidityLayout).setVisibility(View.VISIBLE);
findViewById(R.id.TemperatureLayout).setVisibility(View.GONE);
final LineChartView chartView = (LineChartView) findViewById(R.id.HumidChart);
tsChart = new ThingSpeakLineChart(572138, 2);
tsChart.setListener(new ThingSpeakLineChart.ChartDataUpdateListener() {
@Override
public void onChartDataUpdated(long channelId, int fieldId, String title, LineChartData lineChartData, Viewport maxViewport, Viewport initialViewport) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, -5);
tsChart.setNumberOfEntries(200);
// Set value axis labels on 10-unit interval
tsChart.setValueAxisLabelInterval(10);
// Set date axis labels on 5-minute interval
tsChart.setDateAxisLabelInterval(1);
// Show the line as a cubic spline
tsChart.useSpline(true);
// Set the line color
tsChart.setLineColor(Color.parseColor("#056604"));
// Set the axis color
tsChart.setAxisColor(Color.parseColor("#455a64"));
// Set the starting date (5 minutes ago) for the default viewport of the chart
tsChart.setChartStartDate(calendar.getTime());
chartView.setLineChartData(lineChartData);
chartView.setMaximumViewport(maxViewport);
chartView.setCurrentViewport(initialViewport);
}
});
tsChart.loadChartData();
try {
new FetchThingspeakHumidTask().execute();
}
catch(Exception e){
Log.e("ERROR", e.getMessage(), e);
}
}
});
}
public class FetchThingspeakTempTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
t1.setText("Fetching Data from Server.Please Wait...");
}
protected String doInBackground(Void... urls) {
try {
URL url = new URL(THINGSPEAK_CHANNEL_URL + THINGSPEAK_CHANNEL_ID +
THINGSPEAK_FEEDS_LAST + THINGSPEAK_API_KEY_STRING + "=" +
THINGSPEAK_API_KEY + "");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
//Toast.makeText(MonitoringFragment.this, "There was an error", Toast.LENGTH_SHORT).show();
return;
}
try {
JSONObject channel = (JSONObject) new JSONTokener(response).nextValue();
double v1 = channel.getDouble(THINGSPEAK_FIELD1);
String field1 = Double.toString(v1);
t1.setText(field1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class FetchThingspeakHumidTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
t2.setText("Fetching Data from Server.Please Wait...");
}
protected String doInBackground(Void... urls) {
try {
URL url = new URL(THINGSPEAK_CHANNEL_URL + THINGSPEAK_CHANNEL_ID +
THINGSPEAK_FEEDS_LAST + THINGSPEAK_API_KEY_STRING + "=" +
THINGSPEAK_API_KEY + "");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
// Toast.makeText(MonitoringFragment.this, "There was an error", Toast.LENGTH_SHORT).show();
return;
}
try {
JSONObject channel = (JSONObject) new JSONTokener(response).nextValue();
double v2 = channel.getDouble(THINGSPEAK_FIELD2);
String field2 = new Double(v2).toString();
t2.setText(field2);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
這是我的xml代碼fragment_monitoring.xml,findviewById標記為紅色,在擴展片段中的onCreate方法上執行
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.example.mymonitoring.MonitoringFragment">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGreyTransparent">
<RelativeLayout
android:id="@+id/statsLayoutToolbar"
android:layout_width="match_parent"
android:layout_height="50dp">
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_stats"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:titleTextColor="@color/colorWhite">
</android.support.v7.widget.Toolbar>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100">
<Button
android:id="@+id/btnTemperature"
android:layout_width="130dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:layout_weight="0"
android:gravity="center"
android:text="Temperature" />
<Button
android:id="@+id/btnHumidity"
android:layout_width="130dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:layout_weight="0"
android:gravity="center"
android:text="Humidity" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="449dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="118dp"
android:orientation="vertical"
android:layout_alignParentLeft="true">
<RelativeLayout
android:id="@+id/TemperatureLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include layout="@layout/tempdisplay" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_marginTop="300dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current Temperature :"
android:textColor="@color/colorBlack" />
<TextView
android:id="@+id/tempNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="........"
android:textColor="@color/colorBlack" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Suggestion:"
android:textColor="@color/colorBlack" />
<TextView
android:id="@+id/suggestionTemp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="........"
android:textColor="@color/colorBlack" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="@+id/HumidityLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/humiddisplay" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_marginTop="300dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current Humidity :"
android:textColor="@color/colorBlack" />
<TextView
android:id="@+id/humidNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="........"
android:textColor="@color/colorBlack" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Suggestion:"
android:textColor="@color/colorBlack" />
<TextView
android:id="@+id/suggestionHumid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="........"
android:textColor="@color/colorBlack" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
您正在Fragment(而不是活動findViewById()
中調用findViewById()
。 Fragment沒有可調用的findViewById()
方法。 您將必須在視圖上調用它,如下所示:
view.findViewById(R.id.testId)
如果您沒有片段視圖,則必須在onCreateView()
中將其充氣。 請記住, onCreate()
將在onCreateView()
之前調用。
片段沒有findViewById()
方法,所以它是紅色的,因為它不存在。
必須在View對象上或從Activity(這只是該Activity的根View的代理findViewById()
上調用findViewById()
)。
無論如何,您也無法在Fragment的onCreate()
方法中調用findViewById()
,因為onCreate()
在onCreateView()
之前執行,這意味着Fragment的View在那時為null。
v
在您的Fragment中似乎也不是變量。
將您的代碼移動到onCreateView()
或onViewCreated()
並在View上進行findViewById()
調用。
在片段上,要使用該方法,必須從父視圖中找到ID的地方調用它。
另外,您還必須考慮到視圖是在onCreateView之后創建的,因此您不會在onCreate上找到任何內容,因為該方法是在onCreateView之前調用的。
所以你應該在onCreateView上搜索這樣的視圖
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_monitoring, container, false);
TextView tempNumberTextView = root.findViewById(R.id.tempNumber)
return root;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.