为什么我会得到空指针异常错误?试图从编辑文本传递一个值。

huangapple go评论56阅读模式
英文:

Why am I getting NullPointerException error ? trying to pass a value from an edit text

问题

代码中出现了一个错误,导致应用崩溃的原因是在 ManualSearchActivity 类的成员变量中,EnterCityEditText 的值在 onCreate 方法外部被初始化。这会导致 EnterCityEditText 在初始化时为 null,因此在后续的 doInBackground 方法中使用它时会引发空指针异常。

为了解决这个问题,您应该在 doInBackground 方法内部获取 EnterCityEditText 的值,而不是在类的成员变量中初始化它。以下是修复后的代码:

inner class weatherCall() : AsyncTask<String, Void, String>() {
    override fun onPreExecute() {
        super.onPreExecute()
        findViewById<ProgressBar>(R.id.loader).visibility = View.VISIBLE
        findViewById<RelativeLayout>(R.id.mainRelativeContainer).visibility = View.GONE
        findViewById<TextView>(R.id.ErrorText).visibility = View.GONE
    }

    override fun doInBackground(vararg p0: String?): String? {
        var response: String?
        try {
            val EnterCityEditText = findViewById<EditText>(R.id.enter_city_edit_text).text.toString()
            response = URL("https://api.openweathermap.org/data/2.5/weather?q=$EnterCityEditText&units=metric&APPID=yourapi").readText(Charsets.UTF_8)
        } catch (e: Exception) {
            response = null
        }
        return response
    }

    // ... 省略其余的代码
}

通过在 doInBackground 方法内部获取 EnterCityEditText 的值,您可以解决空指针异常问题,并正确地将城市名称传递到 URL 中,以进行天气查询。感谢David Wasser的提示。

英文:

Manual Search Activity Code:

package com.example.theweathertoday

import android.os.AsyncTask
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import org.json.JSONObject
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*

class ManualSearchActivity : AppCompatActivity()
{


    val API : String = &quot;your api&quot;
    val EnterCityEditText: String = findViewById&lt;EditText&gt;(R.id.enter_city_edit_text).text.toString()

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_manual_search)
        val SearchCityButton = findViewById&lt;Button&gt;(R.id.button_search_city)

        SearchCityButton.setOnClickListener(View.OnClickListener { weatherCall().execute() })

    }


    inner class weatherCall() : AsyncTask&lt;String, Void, String&gt;()
    {
        override fun onPreExecute()
        {
            super.onPreExecute()
            findViewById&lt;ProgressBar&gt;(R.id.loader).visibility = View.VISIBLE
            findViewById&lt;RelativeLayout&gt;(R.id.mainRelativeContainer).visibility = View.GONE
            findViewById&lt;TextView&gt;(R.id.ErrorText).visibility = View.GONE

        }

        override fun doInBackground(vararg p0: String?): String?
        {
            var response:String?
            try
            {
                response = URL( &quot;https://api.openweathermap.org/data/2.5/weather?q=$EnterCityEditText&amp;units=metric&amp;APPID=yourapi&quot;).readText(Charsets.UTF_8)
            }
            catch (e: Exception)
            {
                response = null
            }
            return response
        }

        override fun onPostExecute(result: String?)
        {
            super.onPostExecute(result)
            try
            {
                //JSON Return Values from the API

                val jsonObj = JSONObject(result)
                val main = jsonObj.getJSONObject(&quot;main&quot;)
                val sys = jsonObj.getJSONObject(&quot;sys&quot;)
                val wind = jsonObj.getJSONObject(&quot;wind&quot;)
                val weather = jsonObj.getJSONArray(&quot;weather&quot;).getJSONObject(0)

                val updatedAt:Long = jsonObj.getLong(&quot;dt&quot;)
                val updatedAtText = &quot;Updated at: &quot;+ SimpleDateFormat(&quot;dd/MM/yyyy hh:mm a&quot;, Locale.ENGLISH).format(Date(updatedAt*1000))
                val temp = main.getString(&quot;temp&quot;)+&quot;&#176;C&quot;
                val tempMin = &quot;Min Temp: &quot; + main.getString(&quot;temp_min&quot;)+&quot;&#176;C&quot;
                val tempMax = &quot;Max Temp: &quot; + main.getString(&quot;temp_max&quot;)+&quot;&#176;C&quot;
                val pressure = main.getString(&quot;pressure&quot;)
                val humidity = main.getString(&quot;humidity&quot;)

                val sunrise:Long = sys.getLong(&quot;sunrise&quot;)
                val sunset:Long = sys.getLong(&quot;sunset&quot;)
                val windSpeed = wind.getString(&quot;speed&quot;)
                val weatherDescription = weather.getString(&quot;description&quot;)

                val address = jsonObj.getString(&quot;name&quot;)+&quot;, &quot;+sys.getString(&quot;country&quot;)

                /* Populating extracted data into our views */
                findViewById&lt;TextView&gt;(R.id.location_xml_id).text = address
                findViewById&lt;TextView&gt;(R.id.updated_at_xml_id).text =  updatedAtText
                findViewById&lt;TextView&gt;(R.id.status_xml_id).text = weatherDescription.capitalize()
                findViewById&lt;TextView&gt;(R.id.temperature_xml_id).text = temp
                findViewById&lt;TextView&gt;(R.id.min_temp_xml_id).text = tempMin
                findViewById&lt;TextView&gt;(R.id.max_temp_xml_id).text = tempMax
                findViewById&lt;TextView&gt;(R.id.sunrise).text = SimpleDateFormat(&quot;hh:mm a&quot;, Locale.ENGLISH).format(Date(sunrise*1000))
                findViewById&lt;TextView&gt;(R.id.sunset).text = SimpleDateFormat(&quot;hh:mm a&quot;, Locale.ENGLISH).format(Date(sunset*1000))
                findViewById&lt;TextView&gt;(R.id.wind).text = windSpeed
                findViewById&lt;TextView&gt;(R.id.pressure).text = pressure
                findViewById&lt;TextView&gt;(R.id.humidity).text = humidity

                /* Views populated, Hiding the loader, Showing the main design */
                findViewById&lt;ProgressBar&gt;(R.id.loader).visibility = View.GONE
                findViewById&lt;RelativeLayout&gt;(R.id.mainRelativeContainer).visibility = View.VISIBLE

            } catch (e: Exception) {
                findViewById&lt;ProgressBar&gt;(R.id.loader).visibility = View.GONE
                findViewById&lt;TextView&gt;(R.id.ErrorText).visibility = View.VISIBLE
            }

        }
    }
}

activity_manual_search.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:orientation=&quot;vertical&quot;
android:background=&quot;@drawable/gradient_bg&quot;
tools:context=&quot;.ManualSearchActivity&quot;&gt;
&lt;RelativeLayout
android:id=&quot;@+id/mainRelativeContainer&quot;
android:visibility=&quot;visible&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;&gt;
&lt;LinearLayout
android:id=&quot;@+id/locationContainer&quot;
android:orientation=&quot;vertical&quot;
android:gravity=&quot;center&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;TextView
android:id=&quot;@+id/enter_city_text&quot;
android:text=&quot;Enter City Name: &quot;
android:textSize=&quot;25sp&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot; /&gt;
&lt;EditText
android:id=&quot;@+id/enter_city_edit_text&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_below=&quot;@+id/enter_city_text&quot;
android:maxLines=&quot;1&quot;
android:singleLine=&quot;true&quot;/&gt;
&lt;Button
android:id=&quot;@+id/button_search_city&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;Search for City&quot;
android:layout_gravity=&quot;center&quot;
android:layout_below=&quot;@+id/enter_city_edit_text&quot;
android:layout_centerHorizontal=&quot;true&quot;
android:textColor=&quot;#ffffff&quot;
android:background=&quot;#0048ff&quot;/&gt;
&lt;TextView
android:id=&quot;@+id/location_xml_id&quot;
android:textSize=&quot;25sp&quot;
android:text=&quot;Location&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;TextView
android:id=&quot;@+id/updated_at_xml_id&quot;
android:textSize=&quot;15sp&quot;
android:text=&quot;Updated at&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;/LinearLayout&gt;
&lt;LinearLayout
android:id=&quot;@+id/overviewContainer&quot;
android:orientation=&quot;vertical&quot;
android:layout_centerInParent=&quot;true&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;TextView
android:id=&quot;@+id/status_xml_id&quot;
android:textSize=&quot;35sp&quot;
android:layout_gravity=&quot;center&quot;
android:text=&quot;Clear Sky&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;TextView
android:id=&quot;@+id/temperature_xml_id&quot;
android:textSize=&quot;70sp&quot;
android:fontFamily=&quot;sans-serif-thin&quot;
android:layout_gravity=&quot;center&quot;
android:text=&quot;Temperature&quot;
android:gravity=&quot;center&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;LinearLayout
android:id=&quot;@+id/temperature_min_max_xml_id&quot;
android:orientation=&quot;horizontal&quot;
android:gravity=&quot;center&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;TextView
android:id=&quot;@+id/min_temp_xml_id&quot;
android:text=&quot;Min Temperature&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;Space
android:layout_width=&quot;50dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/Space&gt;
&lt;TextView
android:id=&quot;@+id/max_temp_xml_id&quot;
android:text=&quot;Max Temperature&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;/LinearLayout&gt;
&lt;/LinearLayout&gt;
&lt;LinearLayout
android:id=&quot;@+id/detailsContainer&quot;
android:orientation=&quot;vertical&quot;
android:layout_alignParentBottom=&quot;true&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;LinearLayout
android:orientation=&quot;horizontal&quot;
android:weightSum=&quot;3&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;LinearLayout
android:orientation=&quot;vertical&quot;
android:layout_weight=&quot;1&quot;
android:gravity=&quot;center&quot;
android:padding=&quot;9dp&quot;
android:background=&quot;#969696&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;ImageView
android:layout_width=&quot;25dp&quot;
android:layout_height=&quot;25dp&quot;
android:src=&quot;@drawable/sunrise&quot;
app:tint=&quot;#FFF&quot;&gt;
&lt;/ImageView&gt;
&lt;Space
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;5dp&quot;&gt;
&lt;/Space&gt;
&lt;TextView
android:textSize=&quot;12sp&quot;
android:text=&quot;Sunrise&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;TextView
android:id=&quot;@+id/sunrise&quot;
android:textSize=&quot;14sp&quot;
android:text=&quot;AM&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;/LinearLayout&gt;
&lt;Space
android:layout_width=&quot;10dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/Space&gt;
&lt;LinearLayout
android:orientation=&quot;vertical&quot;
android:layout_weight=&quot;1&quot;
android:gravity=&quot;center&quot;
android:padding=&quot;9dp&quot;
android:background=&quot;#969696&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;ImageView
android:layout_width=&quot;25dp&quot;
android:layout_height=&quot;25dp&quot;
android:src=&quot;@drawable/sunset&quot;
app:tint=&quot;#FFF&quot;&gt;
&lt;/ImageView&gt;
&lt;Space
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;5dp&quot;&gt;
&lt;/Space&gt;
&lt;TextView
android:textSize=&quot;12sp&quot;
android:text=&quot;Sunset&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;TextView
android:id=&quot;@+id/sunset&quot;
android:textSize=&quot;14sp&quot;
android:text=&quot;PM&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;/LinearLayout&gt;
&lt;Space
android:layout_width=&quot;10dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/Space&gt;
&lt;LinearLayout
android:orientation=&quot;vertical&quot;
android:layout_weight=&quot;1&quot;
android:gravity=&quot;center&quot;
android:padding=&quot;9dp&quot;
android:background=&quot;#969696&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;ImageView
android:layout_width=&quot;25dp&quot;
android:layout_height=&quot;25dp&quot;
android:src=&quot;@drawable/wind&quot;
app:tint=&quot;#FFF&quot;&gt;
&lt;/ImageView&gt;
&lt;Space
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;5dp&quot;&gt;
&lt;/Space&gt;
&lt;TextView
android:textSize=&quot;12sp&quot;
android:text=&quot;Wind&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;TextView
android:id=&quot;@+id/wind&quot;
android:textSize=&quot;14sp&quot;
android:text=&quot;Wind&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;/LinearLayout&gt;
&lt;Space
android:layout_width=&quot;10dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/Space&gt;
&lt;/LinearLayout&gt;
&lt;Space
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;10dp&quot;&gt;&lt;/Space&gt;
&lt;LinearLayout
android:orientation=&quot;horizontal&quot;
android:weightSum=&quot;3&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;LinearLayout
android:orientation=&quot;vertical&quot;
android:layout_weight=&quot;1&quot;
android:gravity=&quot;center&quot;
android:padding=&quot;9dp&quot;
android:background=&quot;#969696&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;ImageView
android:layout_width=&quot;25dp&quot;
android:layout_height=&quot;25dp&quot;
android:src=&quot;@drawable/pressure&quot;
app:tint=&quot;#FFF&quot;&gt;
&lt;/ImageView&gt;
&lt;Space
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;5dp&quot;&gt;
&lt;/Space&gt;
&lt;TextView
android:textSize=&quot;12sp&quot;
android:text=&quot;Pressure&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;TextView
android:id=&quot;@+id/pressure&quot;
android:textSize=&quot;14sp&quot;
android:text=&quot;Pressure&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;/LinearLayout&gt;
&lt;Space
android:layout_width=&quot;10dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/Space&gt;
&lt;LinearLayout
android:orientation=&quot;vertical&quot;
android:layout_weight=&quot;1&quot;
android:gravity=&quot;center&quot;
android:padding=&quot;9dp&quot;
android:background=&quot;#969696&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;ImageView
android:layout_width=&quot;25dp&quot;
android:layout_height=&quot;25dp&quot;
android:src=&quot;@drawable/humidity&quot;
app:tint=&quot;#FFF&quot;&gt;
&lt;/ImageView&gt;
&lt;Space
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;5dp&quot;&gt;
&lt;/Space&gt;
&lt;TextView
android:textSize=&quot;12sp&quot;
android:text=&quot;Humidity&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;TextView
android:id=&quot;@+id/humidity&quot;
android:textSize=&quot;14sp&quot;
android:text=&quot;Humidity&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;/LinearLayout&gt;
&lt;Space
android:layout_width=&quot;10dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/Space&gt;
&lt;LinearLayout
android:orientation=&quot;vertical&quot;
android:layout_weight=&quot;1&quot;
android:gravity=&quot;center&quot;
android:padding=&quot;9dp&quot;
android:background=&quot;#969696&quot;
android:layout_width=&quot;0dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;ImageView
android:layout_width=&quot;25dp&quot;
android:layout_height=&quot;25dp&quot;
android:src=&quot;@drawable/info&quot;
app:tint=&quot;#FFF&quot;&gt;
&lt;/ImageView&gt;
&lt;Space
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;5dp&quot;&gt;
&lt;/Space&gt;
&lt;TextView
android:textSize=&quot;12sp&quot;
android:text=&quot;Weather Forecast&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;TextView
android:id=&quot;@+id/info&quot;
android:textSize=&quot;14sp&quot;
android:text=&quot;Next 10 days&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;/LinearLayout&gt;
&lt;Space
android:layout_width=&quot;10dp&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/Space&gt;
&lt;/LinearLayout&gt;
&lt;/LinearLayout&gt;
&lt;/RelativeLayout&gt;
&lt;ProgressBar
android:id=&quot;@+id/loader&quot;
android:layout_centerInParent=&quot;true&quot;
android:visibility=&quot;gone&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/ProgressBar&gt;
&lt;TextView
android:id=&quot;@+id/ErrorText&quot;
android:layout_centerInParent=&quot;true&quot;
android:text=&quot;Error couldn&#39;t connect ?&quot;
android:visibility=&quot;gone&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;&gt;
&lt;/TextView&gt;
&lt;/RelativeLayout&gt;

Error here:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.theweathertoday, PID: 18698
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.theweathertoday/com.example.theweathertoday.ManualSearchActivity}: java.lang.NullPointerException: Attempt to invoke virtual method &#39;android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()&#39; on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method &#39;android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()&#39; on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:173)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:744)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:922)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:889)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:691)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:264)
at com.example.theweathertoday.ManualSearchActivity.&lt;init&gt;(ManualSearchActivity.kt:22)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)&#160;
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)&#160;
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)&#160;
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)&#160;
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)&#160;
at android.os.Handler.dispatchMessage(Handler.java:106)&#160;
at android.os.Looper.loop(Looper.java:223)&#160;
at android.app.ActivityThread.main(ActivityThread.java:7656)&#160;
at java.lang.reflect.Method.invoke(Native Method)&#160;
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)&#160;
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)&#160;

I am trying to pass a value from an edit text to a function, that value is the city name

You can see it inside the URL $EnterCityEditText, I converted the Edit Text entry to String I guess ?

A city name should appear and replace the placeholder value of course

Edit this is the solution, Thanks for David Wasser for hinting

        override fun doInBackground(vararg p0: String?): String?
{
var response:String?
try
{
val EnterCityEditText = findViewById&lt;EditText&gt;(R.id.enter_city_edit_text).text.toString()
response = URL( &quot;https://api.openweathermap.org/data/2.5/weather?q=$EnterCityEditText&amp;units=metric&amp;APPID=yourapi&quot;).readText(Charsets.UTF_8)
}
catch (e: Exception)
{
response = null
}
return response
}

答案1

得分: 0

这是你的问题:

val EnterCityEditText: String = findViewById<EditText>(R.id.enter_city_edit_text).text.toString()

你已经将这个变量声明为类的成员变量。当类的实例被创建时,Android 尝试通过调用 findViewById() 来初始化这个变量。这会失败,因为 Activity 还没有完全初始化(onCreate() 尚未被调用),而且你必须等到调用 setContentView() 之后才能继续。

将变量的初始化移到 onCreate() 中,确保在调用 setContentView() 之后进行初始化。

英文:

This is your problem:

val EnterCityEditText: String = findViewById&lt;EditText&gt;(R.id.enter_city_edit_text).text.toString()

You've declared this variable as a member variable in your class. When the instance of the class is instantiated, Android attempts to initialize this variable by calling findViewById(). This fails because the Activity has not yet been completely initialized (onCreate() has not yet been called) and you must also wait until after setContentView() has been called.

Move the initialization of the variable into onCreate() after you have called setContentView().

答案2

得分: 0

将以下部分翻译为中文:

需要将以下代码:

val EnterCityEditText: String = findViewById<EditText>(R.id.enter_city_edit_text).text.toString()

移动到以下代码之后:

setContentView()

在调用setContentView()之前不能使用findViewById

英文:

You need to move this

> val EnterCityEditText: String =
> findViewById<EditText>(R.id.enter_city_edit_text).text.toString()

after
> setContentView()

You can not use findViewById before "setContentView()"

huangapple
  • 本文由 发表于 2023年2月14日 19:45:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定