2017-02-10 44 views
-2

我試圖使自定義列表,以顯示從數組列表中的數據,但它給了我的NullPointerException在這條線的NullPointerException在自定義列表中的TextView設置數據時

tvtitle.setText(all.get(position).getTitle()); 

都是ArrayList中有對象包含字段標題

這裏是有自定義列表類作爲內部類

package com.heshamkadry.social.app; 

import android.app.ProgressDialog; 
import android.content.Context; 
import android.support.annotation.NonNull; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 

import com.heshamkadry.social.Api.OnTaskCompleteTodo; 
import com.heshamkadry.social.Api.TodoAPI; 
import com.heshamkadry.social.R; 
import com.heshamkadry.social.Users.ToDo; 

import java.util.ArrayList; 

public class TodoView extends AppCompatActivity implements OnTaskCompleteTodo { 
TodoAPI todoAPI; 
ListView lsview; 
ArrayList<ToDo> all; 
String id; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_todo_view); 
    ProgressDialog progressDialog = new ProgressDialog(this); 
    lsview = (ListView) findViewById(R.id.ActivityTodoView_ListView_Todo); 
    todoAPI = new TodoAPI(this , progressDialog); 
    id = getIntent().getStringExtra("id"); 
    todoAPI.execute("?userId="+id); 
} 

@Override 
public void OnCompleteListner() { 
    try 
    { 
     all=todoAPI.get(); 
     CustomAdapter myarrayadapter = new CustomAdapter(this , android.R.layout.simple_list_item_1 , all); 
     lsview.setAdapter(myarrayadapter); 
    }catch (Exception x){ 
     x.printStackTrace(); 
    } 

} 

public class CustomAdapter extends ArrayAdapter 
{ 
    public LayoutInflater inflator; 

    CustomAdapter(Context context , int resourses , ArrayList objects){ 
     super(context,resourses,objects); 
    } 

    @NonNull 
    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     if(inflator == null){ 
      inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     }if(convertView == null){ 
      convertView = inflator.inflate(R.layout.listt_item ,null); 
     } 

     TextView tvtitle = (TextView) convertView.findViewById(R.id.ListItem_TextView_title); 
     TextView tvcoler = (TextView) convertView.findViewById(R.id.ListItem_TextView_coloer); 

     tvtitle.setText(all.get(position).getTitle()); 

     if(all.get(position).isCompleted()){ 
      tvcoler.setBackgroundColor(0xFF00CC00); 
     }else{ 
      tvcoler.setBackgroundColor(0xFF00CCCC); 
     } 
     return convertView; 
    } 
} 
} 

這裏的活動是自定義列表XML

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

<TextView 
    android:text="TextView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentStart="true" 
    android:layout_marginStart="15dp" 
    android:layout_marginTop="19dp" 
    android:id="@+id/ListItem_TextView_title" /> 

<TextView 
    android:text="TextView" 
    android:layout_width="30dp" 
    android:layout_height="30dp" 
    android:layout_alignBottom="@+id/ListItem_TextView_title" 
    android:layout_alignParentEnd="true" 
    android:layout_marginEnd="14dp" 
    android:id="@+id/ListItem_TextView_coloer" 
    android:background="@color/colorAccent" /> 
</RelativeLayout> 

這裏是例外

02-11 12:06:59.356 30758-30758/com.heshamkadry.social E/AndroidRuntime: FATAL EXCEPTION: main 
                     java.lang.NullPointerException 
                      at com.heshamkadry.social.app.TodoView$CustomAdapter.getView(TodoView.java:72) 
                      at android.widget.AbsListView.obtainView(AbsListView.java:2181) 
                      at android.widget.ListView.makeAndAddView(ListView.java:1880) 
                      at android.widget.ListView.fillDown(ListView.java:687) 
                      at android.widget.ListView.fillDown(ListView.java:666) 
                      at android.widget.ListView.fillFromTop(ListView.java:758) 
                      at android.widget.ListView.layoutChildren(ListView.java:1695) 
                      at android.widget.AbsListView.onLayout(AbsListView.java:2016) 
                      at android.view.View.layout(View.java:14471) 
                      at android.view.ViewGroup.layout(ViewGroup.java:4562) 
                      at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076) 
                      at android.view.View.layout(View.java:14471) 
                      at android.view.ViewGroup.layout(ViewGroup.java:4562) 
                      at android.widget.FrameLayout.onLayout(FrameLayout.java:452) 
                      at android.view.View.layout(View.java:14471) 
                      at android.view.ViewGroup.layout(ViewGroup.java:4562) 
                      at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:437) 
                      at android.view.View.layout(View.java:14471) 
                      at android.view.ViewGroup.layout(ViewGroup.java:4562) 
                      at android.widget.FrameLayout.onLayout(FrameLayout.java:452) 
                      at android.view.View.layout(View.java:14471) 
                      at android.view.ViewGroup.layout(ViewGroup.java:4562) 
                      at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671) 
                      at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525) 
                      at android.widget.LinearLayout.onLayout(LinearLayout.java:1434) 
                      at android.view.View.layout(View.java:14471) 
                      at android.view.ViewGroup.layout(ViewGroup.java:4562) 
                      at android.widget.FrameLayout.onLayout(FrameLayout.java:452) 
                      at android.view.View.layout(View.java:14471) 
                      at android.view.ViewGroup.layout(ViewGroup.java:4562) 
                      at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1986) 
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1740) 
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1009) 
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5508) 
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) 
                      at android.view.Choreographer.doCallbacks(Choreographer.java:562) 
                      at android.view.Choreographer.doFrame(Choreographer.java:532) 
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735) 
                      at android.os.Handler.handleCallback(Handler.java:730) 
                      at android.os.Handler.dispatchMessage(Handler.java:92) 
                      at android.os.Looper.loop(Looper.java:213) 
                      at android.app.ActivityThread.main(ActivityThread.java:5225) 
                      at java.lang.reflect.Method.invokeNative(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:525) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) 
                      at dalvik.system.NativeStart.main(Native Method) 

它用簡單的列表視圖

編輯

這裏沒有問題,運行的是待辦事項asynkTask

package com.heshamkadry.social.Api; 

import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.util.Base64; 

import com.heshamkadry.social.Users.ToDo; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 
import org.json.JSONArray; 
import org.json.JSONObject; 

import java.util.ArrayList; 

/** 
* Created by Hesham Kadry on 2/10/2017. 
*/ 

public class TodoAPI extends AsyncTask<String , String ,ArrayList<ToDo>> { 
    ProgressDialog progressDialog; 
    OnTaskCompleteTodo onTaskCompleteTodo; 

    public TodoAPI(OnTaskCompleteTodo onTaskCompleteTodo , ProgressDialog progressDialog){ 
     this.progressDialog = progressDialog; 
     this.onTaskCompleteTodo = onTaskCompleteTodo; 
    } 

    @Override 
    protected void onPreExecute() { 
     progressDialog.setMessage("loading......"); 
     progressDialog.setCancelable(false); 
     progressDialog.show(); 
    } 

    @Override 
    protected ArrayList<ToDo> doInBackground(String... strings) 
    { 
     ArrayList<ToDo> alltodo = new ArrayList<ToDo>(); 

     try 
     { 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet request = new HttpGet("http://jsonplaceholder.typicode.com/todos"+strings[0]); 
      String authorizationString = "Basic " + Base64.encodeToString(
        ("tester" + ":" + "tm-sdktest").getBytes(), 
        Base64.NO_WRAP); 

      request.setHeader("Authorization", authorizationString); 
      HttpResponse response = client.execute(request); 

      HttpEntity entity = response.getEntity(); 

      String result = EntityUtils.toString(entity); 
      int statuescode = response.getStatusLine().getStatusCode(); 

      if(statuescode == 200) 
      { 
       JSONArray jsonArray = new JSONArray(result); 

       for (int counter=0 ; counter<jsonArray.length() ; counter++) 
       { 
        JSONObject jsonObject = jsonArray.getJSONObject(counter); 
        int userid = jsonObject.getInt("userId"); 
        int id = jsonObject.getInt("id"); 
        String title = jsonObject.getString("title"); 
        boolean completed = jsonObject.getBoolean("completed"); 

        ToDo toDo = new ToDo(userid , id , title , completed); 

        alltodo.add(toDo); 
       } 
      } 

     } 
     catch (Exception c) 
     { 
      c.printStackTrace(); 
     } 
     return alltodo; 
    } 

    @Override 
    protected void onPostExecute(ArrayList<ToDo> toDos) { 
     progressDialog.dismiss(); 
     onTaskCompleteTodo.OnCompleteListner(); 
    } 
} 

編輯 解決了錯誤是與自定義列表xml文件的名稱

+0

您的getView方法返回一些空值。 –

+0

顯示您的getCount(),getItemId()等陣列適配器 – Rasel

+0

郵政代碼爲asynctask待辦事項。 –

回答

1

您的ArrayList,「所有」,可能尚未初始化。 That's why you get a nullpointerexception。檢查你在哪裏初始化它,並確保代碼先運行,你應該很好。如果你想確定你的代碼失敗的地方,我建議在帶有斷點的調試器中運行它並逐步完成。

1

在onCreate中實例化您的ArrayList。

all = new Arraylist<>(); 

這很可能會解決您的問題。如果沒有發佈新的堆棧跟蹤

+0

這不是問題 – user3513220

+0

好吧......無論如何這將防止另一個空指針異常 – Kushan

+0

嘗試convertView = LayoutInflater.from(getContext())。 ......刪除你的會員inflater並直接使用它。 – Kushan

相關問題