获取空指针异常

时间:2015-02-14 12:24:48

标签: android android-asynctask nullpointerexception

所以你能告诉我为什么我得到空指针exeptcion。 我正在检查asyncTask是否结束,然后将文本从编辑文本转到arryList之后按钮单击按钮inovks方法myclickhandler1(povijest)并将意图发送到secondActivity,你能告诉我我在这里做错了吗

MainActivity.java

    private static final String DEBUG_TAG = "HttpExample";
    private EditText urlText;
    private TextView textView;
    public int numOfTasks = 0;
    private ArrayList<String> arrayList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        urlText = (EditText) findViewById(R.id.myurl);
        textView = (TextView) findViewById(R.id.mytext);
        textView.setMovementMethod(ScrollingMovementMethod.getInstance());
          arrayList = new ArrayList<String>();



    }


    public void  myClickHandler(View view) {





        String stringUrl = urlText.getText().toString();
        ConnectivityManager connMgr = (ConnectivityManager) 
            getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {


            new DownloadWebpageTask().execute(stringUrl);

        } else {
            textView.setText("No network connection available.");
        }
    }



     public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {




                try {
                    return downloadUrl(urls[0]);
                } catch (IOException e) {
                    return "Unable to retrieve web page. URL may be invalid.";
                }
            }

            @Override
            protected void onPreExecute() 
            {
                    addTask();
                    super.onPreExecute();

            }


            @Override
            protected void onPostExecute(String result) { 
                textView.setText(result);
                removeTask(); 
                allTasksComplete(); 




           }

        }

     private String downloadUrl(String myurl) throws IOException {
            InputStream is = null;


            try {
                URL url = new URL(myurl);
                HttpURLConnection connect = (HttpURLConnection) url.openConnection();
                connect.setReadTimeout(10000 );
                connect.setConnectTimeout(15000 );
                connect.setRequestMethod("GET");
                connect.setDoInput(true);
                connect.connect();
                int response = connect.getResponseCode();
                Log.d(DEBUG_TAG, "The response is: " + response);
                is = connect.getInputStream();


                String contentAsString = readIt(is);
                return contentAsString;


            } finally {
                if (is != null) {
                    is.close();
                } 
            }
     }


    // Reads an InputStream and converts it to a String.
     public String readIt(InputStream stream) throws IOException, UnsupportedEncodingException {
         if (stream != null) {
             StringBuilder sb = new StringBuilder();
             String line;

             try {
                 BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                 while ((line = reader.readLine()) != null) {
                     sb.append(line);
                 }
             } finally {
                 stream.close();
             }
             return sb.toString();
         } else {        
             return "";
         }
     }
     public void myClickHandler1(View povijest){
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            intent.putStringArrayListExtra("arry_list", arrayList);
            startActivity(intent);     
           ;

     }

     public void addTask(){
            numOfTasks++;
        }

        public void removeTask(){
            numOfTasks--;
        }

        public void allTasksComplete()
        {

            if(numOfTasks ==0)
                  {

                arrayList.add(urlText.getText().toString());

            }

        }

SecondActivity.java

package com.example.networking;

import java.util.ArrayList;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SecondActivity extends ActionBarActivity {
     private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondactivity);        
        Intent i = getIntent();  
         ArrayList<String> list = i.getStringArrayListExtra("key");


         lv = (ListView) findViewById(R.id.lista);
         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, list );

         lv.setAdapter(arrayAdapter);


    }

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

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.networking.MainActivity" >

    <EditText
        android:id="@+id/myurl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:inputType="textWebEmailAddress"
        android:ems="10" >

    </EditText>

    <TextView
        android:id="@+id/mytext"
        android:layout_width="200dp"
        android:layout_height="0dp"
        android:layout_marginLeft="38dp"
        android:layout_marginTop="40dp"
        android:layout_weight="0.17"
        android:scrollbars="vertical" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="start"
        android:onClick="myClickHandler1"
        android:text="POVIJEST" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="myClickHandler"
        android:text="Download" />

</LinearLayout>

second_activity.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.networking.SecondActivity" >

    <ListView
        android:id="@+id/lista"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" >
    </ListView>

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

使用arry_list代替key从意图中获取ArrayList:

  ArrayList<String> list = i.getStringArrayListExtra("arry_list");

因为在MainActivity中,arry_list用作在intent中添加ArrayList但在SecondActivity Activity中尝试使用key获取ArrayList的键。