自定义适配器:行膨胀:findViewById返回null

时间:2015-07-14 14:53:14

标签: android layout-inflater findviewbyid

我正在创建一个简单的应用程序,它读取JSON数据并将其显示在ListView中。我创建了一个名为MyAdapter.java的自定义适配器类。我成功地膨胀了行,但是findViewById返回null(在注释中指出)。我计划向Row.xml添加更多wigets,但仅仅是为了测试我添加了TextView。有什么帮助吗?

Row.xml

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

    <TextView
        android:id="@+id/tvnew_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textStyle="italic"/>
</LinearLayout>

MyAdapter.java

package com.test.rajat.contacts;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;


public class MyAdapter extends ArrayAdapter<HashMap<String,String>> {

private ArrayList<HashMap<String,String>> movies_list;
private Context context;
private TextView title;
public MyAdapter(Context context, int        resource,ArrayList<HashMap<String,String>> movies_list) {
    super(context, resource,movies_list);
    this.context=context;
    this.movies_list=movies_list;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v=convertView;
    if(v==null){
        LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.row,null);
        Log.d("IR","row inflated");

    }
    HashMap<String,String> movie=movies_list.get(position);
    if(movie!=null){
        /********This line returns null on findViewById********/
        title=(TextView)v.findViewById(R.id.tvnew_title);
        title.setText(movie.get("title"));
    }
    return v;
}
}

MainActivity.java

package com.test.rajat.contacts;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;


public class MainActivity extends ActionBarActivity {

private ListView list_movies;
private MyAdapter adapter;
private SearchView searchView;
JSONParser parser;
ArrayList<HashMap<String,String>> movies_list;
private static String url="https://api.themoviedb.org/3/search/movie?api_key=<pasted key>&&query=";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list_movies=(ListView) findViewById(R.id.list_movies);
    handleIntent(getIntent());
    parser=new JSONParser();

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchManager searchManager =
            (SearchManager) getSystemService(Context.SEARCH_SERVICE);
     searchView=
            (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setSearchableInfo(
            searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false);
    final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {

            return true;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {

            String newquery=url+query.replaceAll(" ","%20");
            new RetrieveJSON().execute(newquery);
            searchView.clearFocus();
            return true;
        }
    };

    searchView.setOnQueryTextListener(queryTextListener);

    return true;
}
private void handleIntent(Intent intent) {

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        //use the query to search your data somehow
    }
}
@Override
protected void onNewIntent(Intent intent) {

    handleIntent(intent);
}

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

    //noinspection SimplifiableIfStatement
    switch(id)
    {
        case R.id.action_settings:
            return true;
        case R.id.action_search:


    }

    return super.onOptionsItemSelected(item);
}
class RetrieveJSON extends AsyncTask<String,String,Void>
{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        movies_list=new ArrayList<HashMap<String,String>>();
    }

    @Override
    protected Void doInBackground(String... params) {

        String str_json= parser.getJSONFromUrl(params[0]);
        try {
            JSONObject json=new JSONObject(str_json);
            JSONArray jsonArray=new JSONArray(json.getString("results"));
            for(int i=0;i<jsonArray.length();i++)
            {
                JSONObject tmp=jsonArray.getJSONObject(i);
                String title=tmp.getString("title");
                String release_date=tmp.getString("release_date");
                String overview=tmp.getString("overview");
                String rating=tmp.getString("vote_average");
                String poster_path=tmp.getString("poster_path");
                HashMap<String,String> movie=new HashMap<>();
                movie.put("title",title);
                movie.put("release_date",release_date);
                movie.put("overview",overview);
                movie.put("rating",rating);
                movie.put("poster_path",poster_path);
                movies_list.add(movie);

            }

        }

        catch(JSONException e)
        {

        }
       return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        super.onPostExecute(result);
        adapter=new MyAdapter(MainActivity.this,R.layout.row,movies_list);
        list_movies.setAdapter(adapter);

    }
}

}

日志文件

 07-14 19:31:57.182  12606-12606/com.test.rajat.contacts D/IR﹕ row inflated
07-14 19:31:57.183  12606-12606/com.test.rajat.contacts D/AndroidRuntime﹕ Shutting down VM
07-14 19:31:57.189  12606-12606/com.test.rajat.contacts E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.test.rajat.contacts, PID: 12606
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
            at com.test.rajat.contacts.MyAdapter.getView(MyAdapter.java:40)
            at android.widget.AbsListView.obtainView(AbsListView.java:2349)
            at android.widget.ListView.onMeasure(ListView.java:1154)
            at android.view.View.measure(View.java:17554)
            at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1260)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.widget.ScrollView.onMeasure(ScrollView.java:337)
            at android.view.View.measure(View.java:17554)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17554)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
            at android.view.View.measure(View.java:17554)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17554)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17554)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5536)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2871)
            at android.view.View.measure(View.java:17554)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5891)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5293)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

1 个答案:

答案 0 :(得分:1)

改变
   inflater.inflate(R.layout.row,null);

   v= inflater.inflate(R.layout.row,null);

应解决问题