ListView with tabs fragment - setAdapter上的空指针异常

时间:2016-11-15 21:43:07

标签: android listview tabs fragment adapter

我有一个Home活动,带有导航抽屉和3个滑动标签。 我试图在ListView中显示来自数据库的JSON结果,但是当我尝试在listview上设置适配器时,我会在这个上获得空指针异常。

这是家庭活动:

public class HomeActivity extends AppCompatActivity{

DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;

private static final String CHECKLOGIN_URL = "http://achieveme.webutu.com/Php/CheckLogin.php";
private static final String LOGOUT_URL = "http://achieveme.webutu.com/Php/Logout.php";
private static final String GETDATA_URL = "http://achieveme.webutu.com/Php/GetData.php";
private static final String GETACHIEVEMENT_URL = "http://achieveme.webutu.com/Php/GetAchievements.php";

private static TextView tvUsername;
private static TextView tvNumber;
private static TextView tvFollowers;
private static TextView tvFollowing;
private static ListView listView;
private static AchievementAdapter achievementAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mNavigationView = (NavigationView) findViewById(R.id.navView) ;

    mFragmentManager = getSupportFragmentManager();
    mFragmentTransaction = mFragmentManager.beginTransaction();
    mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();

    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            mDrawerLayout.closeDrawers();

            if (menuItem.getItemId() == R.id.Logout) {
                logout();
            }

            return false;
        }

    });

    android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
            R.string.app_name);

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    mDrawerToggle.syncState();

    getAchievement();
}

@Override
protected void onResume(){
    super.onResume();
    getData();
}

@Override
protected void onRestart() {
    super.onRestart();
    checkLogin();
}


private void getData(){
    class GetUser extends AsyncTask<String, Void, String> {
        ProgressDialog loading;
        GetUserClass ruc = new GetUserClass();


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(HomeActivity.this, "Controllo in corso...",null, true, true);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            if(s.matches("")){
                s="Error. Check your Internet connection";
                Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
            }

            else {
                if (!s.matches("Errore") && !s.matches("error")) {
                    tvUsername = (TextView) findViewById(R.id.tvUsername);
                    tvNumber = (TextView) findViewById(R.id.tvNumber);
                    tvFollowers = (TextView) findViewById(R.id.tvFollowers);
                    tvFollowing = (TextView) findViewById(R.id.tvFollowing);

                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONArray jsonArray = jsonObject.getJSONArray("risposta_server");
                        JSONObject jO = jsonArray.getJSONObject(0);
                        String username = jO.getString("username");
                        tvUsername.setText(username);
                        String count_achievements = jO.getString("count_obiettivi");
                        tvNumber.setText(count_achievements);
                        String count_followers = jO.getString("count_seguaci");
                        tvFollowers.setText(count_followers);
                        String count_following = jO.getString("count_seguiti");
                        tvFollowing.setText(count_following);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        }


        @Override
        protected String doInBackground(String... params) {
            SharedPreferences sharedPref = getSharedPreferences("logininfo",Context.MODE_PRIVATE);
            String id= sharedPref.getString("id","");
            String result = ruc.sendGetRequest(GETDATA_URL, id);
            return  result;
        }
    }

    GetUser ru = new GetUser();
    ru.execute();
}


public void getAchievement(){
    class GetUser extends AsyncTask<String, Void, String> {
        ProgressDialog loading;
        GetUserClass ruc = new GetUserClass();


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(HomeActivity.this, "Controllo in corso...",null, true, true);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            if(s.matches("")){
                s="Error. Check your Internet connection";
                Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
            }

            else {
                if (!s.matches("Errore") && !s.matches("error")) {


                    try {
                        listView = (ListView)findViewById(R.id.listview);
                        achievementAdapter = new AchievementAdapter(getApplicationContext(),R.layout.achievement_layout);
                        listView.setAdapter(achievementAdapter);
                        JSONObject jsonObject = new JSONObject(s);
                        JSONArray jsonArray = jsonObject.getJSONArray("risposta_server");
                        String titolo,descrizione;
                        int conto=0;
                        while(conto<jsonArray.length()){
                            JSONObject jO = jsonArray.getJSONObject(conto);
                            titolo = jO.getString("title");
                            descrizione = jO.getString("description");
                            Achievement achievement = new Achievement(titolo,descrizione);
                            achievementAdapter.add(achievement);
                            conto++;
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            }
        }


        @Override
        protected String doInBackground(String... params) {
            SharedPreferences sharedPref = getSharedPreferences("logininfo",Context.MODE_PRIVATE);
            String id= sharedPref.getString("id","");
            String result = ruc.sendGetRequest(GETACHIEVEMENT_URL, id);
            return  result;
        }
    }

    GetUser ru = new GetUser();
    ru.execute();
}
}

这是适配器:

public class AchievementAdapter extends ArrayAdapter {
List lista = new ArrayList();
public AchievementAdapter(Context context, int resource) {
    super(context, resource);
}

public void add(Achievement object) {
    super.add(object);
    lista.add(object);
}

@Override
public int getCount() {
    return lista.size();
}

@Override
public Object getItem(int position) {
    return lista.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row;
    row=convertView;
    AchievementHolder achievementHolder;

    if(row==null){
        LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row=layoutInflater.inflate(R.layout.achievement_layout,parent,false);
        achievementHolder = new AchievementHolder();
        achievementHolder.txTitle = (TextView) row.findViewById(R.id.title);
        achievementHolder.txDescription = (TextView) row.findViewById(R.id.description);
        row.setTag(achievementHolder);
    }
    else {
        achievementHolder=(AchievementHolder)row.getTag();
    }
    Achievement achievement = (Achievement) this.getItem(position);
    achievementHolder.txTitle.setText(achievement.getTitle());
    achievementHolder.txDescription.setText(achievement.getDescription());
    return row;
}

static class AchievementHolder{
    TextView txTitle,txDescription;
}
}

以下是成就课:

public class Achievement {
private String title,description;

public Achievement(String title, String description){
    this.setTitle(title);
    this.setDescription(description);
}
public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}
}

这里是3个片段中的一个(我要在其中显示listView):

public class FragmentObiettivi extends Fragment{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_obiettivi, container, false);

    return rootView;
}
}

这里是上面片段的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="wrap_content">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listview">
    </ListView>

</LinearLayout>

这里是logcat:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.gianluca.achieveme, PID: 26385
              java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                  at com.example.gianluca.achieveme.HomeActivity$2GetUser.onPostExecute(HomeActivity.java:282)
                  at com.example.gianluca.achieveme.HomeActivity$2GetUser.onPostExecute(HomeActivity.java:255)
                  at android.os.AsyncTask.finish(AsyncTask.java:632)
                  at android.os.AsyncTask.access$600(AsyncTask.java:177)
                  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:135)
                  at android.app.ActivityThread.main(ActivityThread.java:5306)
                  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:899)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

第282行是listView.setAdapter(achievementAdapter);
请帮助我,这件事让我发疯,因为

                tvUsername = (TextView) findViewById(R.id.tvUsername);
                tvNumber = (TextView) findViewById(R.id.tvNumber);
                tvFollowers = (TextView) findViewById(R.id.tvFollowers);
                tvFollowing = (TextView) findViewById(R.id.tvFollowing);

是其他2个标签片段之一的其他视图,我对它们执行setText没有任何问题。

0 个答案:

没有答案