2015-09-03 30 views
-3

請通過下面的代碼和幫助我。來自url的數據被解析,但我無法填充到列表視圖。獲得空指針EXCETION雖然將數據填充到列表視圖

public class HomeFragment extends Fragment { 
View rootView = null; 
private ListView myListView; 
private String[] strListView; 
private String[] categ; 
private TextView catName; 
private CustomAdapter myAdapter; 
private DownloadJson downloadJson; 

private int i; 
private AsyncTask task; 
private Thread thread; 
public HomeFragment() 
{ 

} 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setHasOptionsMenu(true); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    rootView = inflater.inflate(R.layout.fragment_home, container, false); 
    myListView = (ListView) rootView.findViewById(R.id.listview); 

    new DownloadJson().execute(); 


    // Inflate the layout for this fragment 
    return rootView; 
} 

這是callCustomAdapter功能:

public void callCustomAdaper(Context context) 
{ 
    myAdapter = new CustomAdapter(context); 
    myListView.setAdapter(myAdapter); 
    myListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() { 

     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      Log.v("Module Item Trigger", "Module item was triggerted"); 


      /* Fragment customMapFragmentMapFragment = new MessagesFragment(); 

      FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
      fragmentManager.beginTransaction() 

        .replace(R.id.container, customMapFragmentMapFragment) 
        .addToBackStack(null) 
        .commit();*/ 
     } 
    }); 
} 

這個類是JSON解析器:

class DownloadJson extends AsyncTask { 

    Activity context; 
    ListView myListView; 

    private ProgressDialog dialog = new ProgressDialog(getActivity()); 
    public DownloadJson(Activity context, ListView myListView) { 
     this.myListView = myListView; 
     this.context = context; 

    } 

    public DownloadJson() { 

    } 


    @Override 
    protected void onPreExecute() { 

     this.dialog.setMessage("Please wait"); 
     this.dialog.show(); 
    } 


    @Override 
    protected void onCancelled() { 
     super.onCancelled(); 
    } 

    @Override 
    protected Object doInBackground(Object[] params) { 
     String result = null; 
     InputStream isr = null; 
     String imageId = null; 
     String ip = "http://ganarajsshetti.tk/mobileapp/selectjson.php/"; 
     try { 

      HttpClient httpClient = new DefaultHttpClient(); 
      HttpGet httpGet = new HttpGet(ip); 
      HttpResponse httpResponse = httpClient.execute(httpGet); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      isr = httpEntity.getContent(); 
     } catch (Exception e) { 
      Log.e("log_tag", "Error in http Connection" + e.toString()); 

     } 
     // converting response to string 
     try { 
      BufferedReader br = new BufferedReader(new InputStreamReader(isr)); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = br.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      isr.close(); 
      result = sb.toString(); 

     } catch (Exception e) { 
      Log.e("log_tag", "Error in Converting Data" + e.toString()); 
     } 

     // parse JSON data 

     try { 

      JSONArray jsonArray = new JSONArray(result); 
      strListView = new String[jsonArray.length()]; 
      for (int i = 0; i < jsonArray.length(); i++) { 
       JSONArray json_data = jsonArray.getJSONArray(i); 
       for (int j =0; j< json_data.length();j++) { 

        strListView[i] = json_data.getString(j); 

        System.out.println("--------------" + json_data.getString(0)); 

       } 
       Log.e("ACK_tag", "DATA" + strListView[i]); 
      } 

     } catch (Exception e) { 
      Log.e("log_tag", "Error in parsing Data" + e.toString()); 
     } 

     return null; 

    } 

    @Override 
    protected void onPostExecute(Object o) { 
    // ArrayAdapter objAdapter = new ArrayAdapter<String>(context,R.layout.list_item,R.id.Category,strListView); 
     if (dialog.isShowing()) { 
      dialog.dismiss(); 
     } 

     callCustomAdaper(context); 
    } 
} 

這是我customAdapter延伸底座適配器:

public class CustomAdapter extends BaseAdapter { 
    private Context context; 


    public CustomAdapter(Context context) { 
     this.context = context; 

    } 

    @Override 
    public int getCount() { 
     return strListView.length; 
    } 

    @Override 
    public Object getItem(int i) { 
     return strListView[i]; 
    } 

    @Override 
    public long getItemId(int i) { 
     return i; 
    } 

    @Override 
    public View getView(int i, View convertview, ViewGroup viewGroup) { 
     View row= null; 

     if(convertview == null) { 
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      row = inflater.inflate(R.layout.list_item, viewGroup, false); 
     } 
     else{ 
      row= convertview; 

     } 
     catName=(TextView) row.findViewById(R.id.Category); 
     catName.setText(categ[i]); 
     return row; 
    } 
    public String[] getValues() 
    { 
     return strListView; 
    } 
} 

這是我的XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context="info.androidhive.materialdesign.activity.HomeFragment"> 

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

</RelativeLayout> 

這是其他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="10dp" 
    android:paddingLeft="10dp" 
    android:paddingRight="10dp"> 

    <TextView 
     android:id="@+id/Category" 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:gravity="center_horizontal" 

     android:textStyle="bold"/> 



</LinearLayout> 

這是我收到的錯誤:

顯示java.lang.NullPointerException:嘗試上的空對象引用 在info.androidhive.materialdesign.activity.HomeFragment $ CustomAdapter.getView(HomeFragment.java:248調用虛擬方法java.lang.Object中android.content.Context.getSystemService(java.lang.String中)' )

+0

在其中添加在CATEG [I]值????? –

+0

要添加在strListView和getView你取出由CATEG [I] –

+0

使用上下文的背景下,而不是活動方面的 – Rajesh

回答

0

沒有與您的上下文傳遞到您的適配器的問題。在您的片段中,您打電話給new DownloadJson().execute();因此,您不會將上下文發送到AsyncTask,因此無法將其發送到適配器。您應該使用另一個構造new DownloadJson(getActivity(), myListView).execute();

還有一件事你should't活動保存爲背景。當你不需要時,你正在泄漏將它保存在內存中的活動。在您的AsyncTask使用private Context context;並獲得該上下文關係getActivity().getApplicationContext();

+0

非常感謝,它工作得很好:) –

0

你正在創建DownloadJson與錯誤的構造(空單)