2015-02-14 2 views
-1

Так вы можете сказать мне, почему я получаю исключение нулевого указателя. Я проверяю, если AsyncTask закончены, а затем получить текст из редактирования текста в arryList после этого на кнопку мыши метод кнопки inovks myclickhandler1 (povijest) и посылает намерение secondActivity вы можете сказать мне, что я делаю неправильно здесьПолучение нулевого указателя exeptcion

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> 
+0

, который линии вашего получения. post log cat – KomalG

+0

ok теперь он работает – lacky01

ответ

0

Использование arry_list вместо key, чтобы получить ArrayList от намерения:

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

Поскольку в MainActivity активность arry_list используется в качестве ключа для добавления ArrayList в но в SecondActivity Деятельность пытается получить Arr ayList с использованием key.

+0

Спасибо за это, вы боролись с этим весь день, и это было просто так – lacky01

Смежные вопросы