Android TextView的ListView活动侦听器空指针异常

Android TextView的ListView活动侦听器空指针异常,android,listview,onitemclicklistener,Android,Listview,Onitemclicklistener,我想当我点击特定行时,文本应该被复制并粘贴到另一个活动中。我已经实现了代码,但有一件事导致空指针异常。请帮助我 //@Override // listening to single list item on click listview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterVi

我想当我点击特定行时,文本应该被复制并粘贴到另一个活动中。我已经实现了代码,但有一件事导致空指针异常。请帮助我

//@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);

          }
        });
主要活动

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

您可以使用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);
          }
          }

      }
@覆盖
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
如果(视图!=null){
//选定项目
text=(TextView)view.findViewById(R.id.title);
if(text!=null&&text.getText()!=null){
字符串lst_txt=text.getText().toString().trim();
//字符串product=((TextView)view.findViewById(R.id.targetmonth)).getText().toString();
System.out.println(“文本”+lst_txt);
//在选择单个列表项时启动新活动
意图i=新意图(MainActivity.this,SingleListItem.class);
//向新活动发送数据
i、 putExtra(“产品”,lst_txt);
星触觉(i);
}
}
}

另外,作为旁注,请在每个in代码注释前加一行新行,或者完全避免使用它们。

更改您的项目单击侦听器,如下所示,然后查看是否有效:

更新代码

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); 

    }
});
listview.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
//选定项目
TextView text=(TextView)view.findViewById(R.id.targetmonths);
String lst_txt=String.valueOf(text.getText());
System.out.println(“显示文本”+lst_txt);
//在选择单个列表项时启动新活动
意图i=新意图(MainActivity.this,SingleListItem.class);
//向新活动发送数据
i、 putExtra(“产品”,lst_txt);
星触觉(i);
}
});
您获得NPE是因为当您为该列表视图创建
适配器时,您正在传递
android.R.layout.simple\u list\u item\u 1
在此布局中没有id为
title的
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
     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);
   }
});
/@覆盖
//在单击时侦听单个列表项
setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
int位置,长id){
//选定项目
字符串lst_txt=parent.getItemAtPosition(position.toString().trim();
System.out.println(“显示文本”+lst_txt);
//在选择单个列表项时启动新活动
意图i=新意图(MainActivity.this,SingleListItem.class);
//向新活动发送数据
i、 putExtra(“产品”,lst_txt);
星触觉(i);
}
});




是否可以尝试仅列出项单击listener@sakir不,它不适用于代码它在eclipse中给出红线OnListItemClick无法解析为类型您试图在onCreate方法中重写OnListItemClick方法如果是,将其置于create方法之外实际上TextView text=(TextView)视图。findViewById(R.id.title);导致空指针异常且无getItem未给出空值是否100%确定这是这一行而不是下一行?是101%确定我已对其进行了测试。它从此端终止程序,现在?我添加了另一个条件getText()方法对于类型视图是未定义的,它在下面显示getText条件的此消息代码未执行,但它删除了错误,但如果(View!=null&&View.findViewById(R.id.title)instanceof TextView)仍然是文本未获取{你能分享你的适配器和xml文件适配器中使用的xml文件吗?没有roleNo,我要问两件事,适配器中使用的xml和适配器java文件,通过编辑你的问题并在这里留下确认评论来分享。.谢谢KAushik,如果你能告诉我,它就像一个问题一样有效。我在lis中有链接tview但不是show hyperlink。我可以显示超链接吗?然后你必须自定义你的适配器,而不是android.R.layout。simple_list_item_1
必须为Row使用自定义布局我同意,但如何自定义我已将simple_list_item_1更改为具有相同属性的其他xml,但eclipse显示红线如何使用自定义来自定义它适配器并显示工作的超链接
ArrayAdapter adapter=new ArrayAdapter(活动,android.R.layout.simple_list_item_1,twits);setlistapter(适配器)
你能用
CustomAdapter
custom\u layout
编辑你的问题或问另一个问题吗?我已经提出了我的问题,很抱歉回复太晚,这里是[链接]
        @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);
          }
          }

      }
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); 

    }
});
//@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);
   }
});
<?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"
/>