Деятельность управления ListView OnItemClickListener исключение нулевого указателя на элемент TextView


Я хочу, чтобы при нажатии на определенную строку текст должен быть скопирован и вставлен в другое действие по намерению действия.Я реализовал код, но одна вещь вызывает исключение нулевого указателя.Пожалуйста, помогите мне.

//@Override
         // listening to single list item on click
      listview.setOnItemClickListener(new OnItemClickListener() {
          @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

              // selected item
            TextView  text = (TextView) view.findViewById(R.id.title);
              String lst_txt = text.getText().toString().trim();

             System.out.println("Display text"+lst_txt ); 
              // Launching new Activity on selecting single List Item
              Intent i = new Intent(MainActivity.this, SingleListItem.class);
              // sending data to new activity
              i.putExtra("product",lst_txt );
              startActivity(i);

          }
        });

// здесь текстовое поле TextView = (виджет TextView) смотреть.команду findViewById(Р. ИД.название); причиной нулевой указатель исключение

Logcat

12-12 07:41:25.459: E/AndroidRuntime(2326): FATAL EXCEPTION: main
12-12 07:41:25.459: E/AndroidRuntime(2326): java.lang.NullPointerException
12-12 07:41:25.459: E/AndroidRuntime(2326):     at com.example.TwitterTutorial.MainActivity$1.onItemClick(MainActivity.java:70)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at android.widget.AdapterView.performItemClick(AdapterView.java:298)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at android.widget.AbsListView$1.run(AbsListView.java:3423)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at android.os.Handler.handleCallback(Handler.java:725)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at android.os.Looper.loop(Looper.java:137)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at android.app.ActivityThread.main(ActivityThread.java:5039)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at java.lang.reflect.Method.invokeNative(Native Method)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at java.lang.reflect.Method.invoke(Method.java:511)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-12 07:41:25.459: E/AndroidRuntime(2326):     at dalvik.system.NativeStart.main(Native Method)

Основная Деятельность

public class MainActivity extends ListActivity {

private ListActivity activity;
final static String ScreenName = "bane";
final static String LOG_TAG = "rnc";
 ListView listview;
  TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

//  setContentView(R.layout.twit_list);

    // listView.setTextFilterEnabled(true);


     activity = this;
      listview = this.getListView();
    downloadTweets();

          listview.setOnItemClickListener(new OnItemClickListener() {
      @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
          if(view != null && view.getContext() != null){

          // selected item
          //text = (TextView) view.findViewById(R.id.title);
         // String lst_txt = text.getText().toString().trim();

           String product = ((TextView) view.findViewById(R.id.targetmonths)).getText().toString();
          //System.out.println("Text"+lst_txt ); 

          // Launching new Activity on selecting single List Item
          Intent i = new Intent(MainActivity.this, SingleListItem.class);

          // sending data to new activity
          i.putExtra("product",product );
          startActivity(i);
          }

    }

    // download twitter timeline after first checking to see if there is a network connection
    public void downloadTweets() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            new DownloadTwitterTask().execute(ScreenName);
        } else {
            Log.v(LOG_TAG, "No network connection available.");
        }
    }

    // Uses an AsyncTask to download a Twitter user's timeline
    private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
        final static String CONSUMER_KEY = "3GsPNkJacZedXIwoajycHzkkU";
        final static String CONSUMER_SECRET = "kCsPxxjsfrwba4cSZWW0tmXvaIcWT6r5Gb2HD5VX3RDYoDGRfXG";
        final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
        final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";

        @Override
        protected String doInBackground(String... screenNames) {
            String result = null;

            if (screenNames.length > 0) {
                result = getTwitterStream(screenNames[0]);
            }
            return result;
        }

        // onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
        @Override
        protected void onPostExecute(String result) {
            Twitter twits = jsonToTwitter(result);

            // lets write the results to the console as well
            for (Tweet tweet : twits) {
                Log.i(LOG_TAG, tweet.getText());
            }

            // send the tweets to the adapter for rendering
            ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, android.R.layout.simple_list_item_1, twits);
            setListAdapter(adapter);
        }

        // converts a string of JSON data into a Twitter object
        private Twitter jsonToTwitter(String result) {
            Twitter twits = null;
            if (result != null && result.length() > 0) {
                try {
                    Gson gson = new Gson();
                    twits = gson.fromJson(result, Twitter.class);
                } catch (IllegalStateException ex) {
                    // just eat the exception
                }
            }
            return twits;
        }

        // convert a JSON authentication object into an Authenticated object
        private Authenticated jsonToAuthenticated(String rawAuthorization) {
            Authenticated auth = null;
            if (rawAuthorization != null && rawAuthorization.length() > 0) {
                try {
                    Gson gson = new Gson();
                    auth = gson.fromJson(rawAuthorization, Authenticated.class);
                } catch (IllegalStateException ex) {
                    // just eat the exception
                }
            }
            return auth;
        }

        private String getResponseBody(HttpRequestBase request) {
            StringBuilder sb = new StringBuilder();
            try {

                DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
                HttpResponse response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                String reason = response.getStatusLine().getReasonPhrase();

                if (statusCode == 200) {

                    HttpEntity entity = response.getEntity();
                    InputStream inputStream = entity.getContent();

                    BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    String line = null;
                    while ((line = bReader.readLine()) != null) {
                        sb.append(line);
                    }
                } else {
                    sb.append(reason);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (ClientProtocolException ex1) {
            } catch (IOException ex2) {
            }
            return sb.toString();
        }

        private String getTwitterStream(String screenName) {
            String results = null;

            // Step 1: Encode consumer key and secret
            try {
                // URL encode the consumer key and secret
                String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
                String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");

                // Concatenate the encoded consumer key, a colon character, and the
                // encoded consumer secret
                String combined = urlApiKey + ":" + urlApiSecret;

                // Base64 encode the string
                String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

                // Step 2: Obtain a bearer token
                HttpPost httpPost = new HttpPost(TwitterTokenURL);
                httpPost.setHeader("Authorization", "Basic " + base64Encoded);
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
                String rawAuthorization = getResponseBody(httpPost);
                Authenticated auth = jsonToAuthenticated(rawAuthorization);

                // Applications should verify that the value associated with the
                // token_type key of the returned object is bearer
                if (auth != null && auth.token_type.equals("bearer")) {

                    // Step 3: Authenticate API requests with bearer token
                    HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);

                    // construct a normal HTTPS request and include an Authorization
                    // header with the value of Bearer <>
                    httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
                    httpGet.setHeader("Content-Type", "application/json");
                    // update the results with the body of the response
                    results = getResponseBody(httpGet);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (IllegalStateException ex1) {
            }
            return results;
        }
    }
}

Xml-файл, используемый для отображения listview

<?xml version="1.0" encoding="utf-8"?>

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@android:id/list"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">

</ListView>

Адаптер Данных

public class DataAdapter extends BaseAdapter {
    Context mContext; 
    private LayoutInflater mInflater;
    String targetmonths;
    //String img;
    //String targetamount; 
    String[] month;
    //String[] year;
    //String[] amount;
    public DataAdapter(Context c, String[] month) {
        this.month = month;
        //this.year = year;
        //this.amount = amount; 
        mContext = c;
        mInflater = LayoutInflater.from(c); 
    } 
    public int getCount() {
        return month.length;
    } 
    public Object getItem(int position) {
        return position;
    } 
    public long getItemId(int position) {
        return position;
    } 
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.customgrid, parent, false);
            holder = new ViewHolder();
            holder.month = (TextView) convertView
                    .findViewById(R.id.targetmonths); 

            //holder.img = (ImageView) convertView.findViewById(R.id.image_id); 
        //  holder.amount = (TextView) convertView.findViewById(R.id.targetamount); 




            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        try {

            holder.month.setText(month[position]);




    //      holder.img.setImageResource(img[position]);
        //  holder.amount.setText(amount[position]);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        return convertView;
    } 
    static class ViewHolder {
        TextView month;
    //  ImageView img;
    //  TextView year, amount; 
    }

}

Пользовательская Сетка

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

            <TextView
                android:id="@+id/targetmonths"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_gravity="left"
                android:layout_weight="1"
                android:gravity="left|center"
                android:paddingBottom="5sp"
                android:paddingLeft="10sp"
                android:paddingRight="5sp"
                android:paddingTop="5sp"
                android:text="hello"
                android:textColor="#ffffcc"
                android:textSize="16sp">
            </TextView>
        </LinearLayout>
4 3

4 ответа:

Вы получаете NPE , потому что при создании Adapter этого listview вы передаете android.R.layout.simple_list_item_1 в этом макете нет TextView с идентификатором title

Поэтому измените свой onItemClick следующим образом

//@Override
// listening to single list item on click
listview.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> parent, View view,
               int position, long id) {   
     // selected item
     String lst_txt = parent.getItemAtPosition(position).toString().trim();

     System.out.println("Display text"+lst_txt ); 
     // Launching new Activity on selecting single List Item
     Intent i = new Intent(MainActivity.this, SingleListItem.class);
     // sending data to new activity
     i.putExtra("product",lst_txt );
     startActivity(i);
   }
});

код Grep для android.Р. макет.simple_list_item_1

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
/>

Измените свой элемент click listener, как показано ниже, и посмотрите, работает ли это:

Обновленный код

listview.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {

        // selected item          
            TextView text = (TextView) view.findViewById(R.id.targetmonths);
            String lst_txt = String.valueOf(text.getText());

            System.out.println("Display text"+lst_txt );
            // Launching new Activity on selecting single List Item
            Intent i = new Intent(MainActivity.this, SingleListItem.class);
            // sending data to new activity
            i.putExtra("product",lst_txt );
            startActivity(i); 

    }
});

Можно использовать событие onListItemClick

protected void onListItemClick (ListView l, View v, int position, long id){
    super.onListItemClick(l, v, position, id);

        }

Возвращает ли метод getItem() в вашем адаптере значение null? Если да, измените его так, чтобы он возвращал допустимое представление, и повторите попытку.

Попробуйте сделать это и скажите мне, что происходит:

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
          if(view != null){

          // selected item
          text = (TextView) view.findViewById(R.id.title);
          if(text != null && text.getText() != null){
              String lst_txt = text.getText().toString().trim();

              // String product = ((TextView) view.findViewById(R.id.targetmonth)).getText().toString();
              System.out.println("Text"+lst_txt ); 

              // Launching new Activity on selecting single List Item
              Intent i = new Intent(MainActivity.this, SingleListItem.class);

              // sending data to new activity
              i.putExtra("product",lst_txt );
              startActivity(i);
          }
          }

      }

Кроме того, в качестве дополнительного Примечания, пожалуйста, поставьте новую строку перед каждым комментарием в коде, или вообще избегайте их.