NullPointerExcepter Error when using List Adapter and Custom List View in Android Studio

浪尽此生 提交于 2020-01-16 07:18:05

问题


Been trying to write an app in android studio. Part of the app has to parse a document in JSON and display two TextViews of data for each instance. One being Signal and the other being Noise. I am trying to make a custom list view in case I want to add more detail to each instance. I also would like to make it all contained in a ScrollView. I initially had no problems parsing the document but now that I am trying to implement the ListAdapter I am running into issues.

My code is giving me the error...

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.yesinc.tsi880, PID: 4919
                  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                      at com.yesinc.tsi880.TelemetryActivity$JSONTask.onPostExecute(TelemetryActivity.java:136)
                      at com.yesinc.tsi880.TelemetryActivity$JSONTask.onPostExecute(TelemetryActivity.java:50)

Not sure if the problem is with the document that I am trying to parse or the java code itself. Any help would be much appreciated. Code is below.

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.yesinc.tsi880.models.SondeModel;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;




import android.widget.ArrayAdapter;



public class TelemetryActivity extends AppCompatActivity {

    private TextView tvData;
    private ListView lvSondes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_telemetry);

        ListView lvSondes = findViewById(R.id.lvSondes);

        //new JSONTask().execute("http://172.16.5.70/plots/sigstr2.txt");
    }

    public class JSONTask extends AsyncTask<String, String, List<SondeModel> >{

        @Override
        protected List<SondeModel> doInBackground(String... params) {
            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();

                String line;
                while((line=reader.readLine()) != null){
                    buffer.append(line);
                }

                String finalJson = buffer.toString();

                JSONObject parentObject = new JSONObject(finalJson);
                JSONObject parentArray0 = parentObject.getJSONObject("0");
                JSONObject parentArray1 = parentObject.getJSONObject("1");

                List<SondeModel> sondeModelList = new ArrayList<>();

                //StringBuffer finalBufferedData = new StringBuffer();
                for(int i=0; i<8; i++){

                    String sonde = String.valueOf(i);
                    JSONObject finalObject = parentArray0.getJSONObject(sonde);
                    SondeModel sondeModel = new SondeModel();
                    sondeModel.setNoisedbm(finalObject.getString("noisedbm"));
                    sondeModel.setSigdbm(finalObject.getString("sigdbm"));

                    //String noiseDBM = finalObject.getString("noisedbm");
                    //String sigDBM = finalObject.getString("sigdbm");

                    sondeModelList.add(sondeModel);
                }

                for(int i=0; i<8; i++){

                    String sonde = String.valueOf(i);
                    JSONObject finalObject = parentArray1.getJSONObject(sonde);
                    SondeModel sondeModel = new SondeModel();
                    sondeModel.setNoisedbm(finalObject.getString("noisedbm"));
                    sondeModel.setSigdbm(finalObject.getString("sigdbm"));

                    //String noiseDBM = finalObject.getString("noisedbm");
                    //String sigDBM = finalObject.getString("sigdbm");

                    sondeModelList.add(sondeModel);
                }
                return sondeModelList;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if(connection != null) {
                    connection.disconnect();
                }try {
                    if(reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(List<SondeModel> result) {
            super.onPostExecute(result);

            SondeAdapter adapter = new SondeAdapter(getApplicationContext(), R.layout.row, result);
            lvSondes.setAdapter(adapter);

            // TODO need to set a data to the List
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.navigation, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.navigation_telemetry) {
            new JSONTask().execute("http://172.16.5.70/plots/sigstr2.txt");
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class SondeAdapter extends ArrayAdapter{
        public List<SondeModel> sondeModelList;
        private int resource;
        private LayoutInflater inflater;
        public SondeAdapter(Context context, int resource, List<SondeModel> objects) {
            super(context, resource, objects);
            sondeModelList = objects;
            this.resource = resource;
            inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        }



        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if(convertView == null){
                convertView = inflater.inflate(resource, null);
            }

            TextView sig;
            TextView noise;

            sig = (TextView)convertView.findViewById(R.id.sig);
            noise = (TextView)convertView.findViewById(R.id.noise);

            sig.setText(sondeModelList.get(position).getSigdbm());
            noise.setText(sondeModelList.get(position).getNoisedbm());

            return convertView;
        }
    }

}

回答1:


ListView lvSondes = findViewById(R.id.lvSondes);

You are re-declaring the lvSondes inside your onCreate method. The class member list view is never used and is never initialized. Instead a local lvSondes is initialized. This variable will not be in scope and won't be visible to the AsyncTask. The async task will use the member variable and that will be null.

Solution: remove the ListView from the stated line and just initialize the member variable



来源:https://stackoverflow.com/questions/51369637/nullpointerexcepter-error-when-using-list-adapter-and-custom-list-view-in-androi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!