I have a problem with parsing JSON data into listFragment. I tried this with TabBar but im trying to fix it with Fragments ....
this is the class that should get data into a listview :
public class Dieta extends ListFragment {
private ListView getAllPacientiListView;
private JSONArray jsonArray;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_a, container, false);
getAllPacientiListView = (ListView) v.findViewById(android.R.id.list);
new GetAllPacientiTask().execute(new ApiConnector());
getAllPacientiListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
try{
//Get the pacienti which was clicked
JSONObject pacientiClicked = jsonArray.getJSONObject(position);
//Send Pacienti ID
Intent showDetails = new Intent(getActivity().getApplicationContext(),PacientiDetailsActivity.class);
showDetails.putExtra("PacientiID", pacientiClicked.getInt("pacienti_id"));
startActivity(showDetails);
}
catch(JSONException e ){
e.printStackTrace();
}
}
});return v;
}
public void setListAdapter(JSONArray jsonArray){
this.jsonArray = jsonArray;
getAllPacientiListView.setAdapter(new GetAllPacientiListViewAdapter(jsonArray,getActivity()));
}
private class GetAllPacientiTask extends AsyncTask<ApiConnector,Long,JSONArray> {
@Override
protected JSONArray doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].GetAllPacienti();
}
@Override
protected void onPostExecute(JSONArray jsonArray){
setListAdapter(jsonArray);
}
}
}
this is ApiConnector class :
public class ApiConnector {
public JSONArray GetAllPacienti(){
// URL for getting all costumers
String url = "http://..../ushtrime1/getAllPacienti.php";
//Get HTTPResponse Object from URL
//Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
try{
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default httpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch(ClientProtocolException e){
e.printStackTrace();
//Log Errors Here
} catch(IOException e ){
e.printStackTrace();
}
//Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if(httpEntity != null){
try{
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray (entityResponse);
}catch (JSONException e ){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
return jsonArray;
}
public JSONArray GetPacientiDetails(int PacientiID){
// URL for getting all costumers
String url = "http://...../ushtrime1 /getPacientiDetails.php?PacientiID="+PacientiID;
//Get HTTPResponse Object from URL
//Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
try{
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default httpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch(ClientProtocolException e){
e.printStackTrace();
//Log Errors Here
} catch(IOException e ){
e.printStackTrace();
}
//Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if(httpEntity != null){
try{
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray (entityResponse);
}catch (JSONException e ){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
return jsonArray;
}
}
and this is getAllPacientiListView class :
public class GetAllPacientiListViewAdapter extends BaseAdapter{
private JSONArray dataArray;
private Activity activity;
private static LayoutInflater inflater = null;
public GetAllPacientiListViewAdapter(JSONArray jsonArray, Activity a){
this.dataArray = jsonArray;
this.activity = a;
inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return this.dataArray.length();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListCell cell;
if(convertView == null){
convertView = inflater.inflate(R.layout.get_all_pacienti_list_view, null);
cell = new ListCell();
cell.FullName = (TextView) convertView.findViewById(R.id.pacienti_full_name);
convertView.setTag(cell);
}
else{
cell = (ListCell) convertView.getTag();
}
try {
JSONObject jsonObject = this.dataArray.getJSONObject(position);
cell.FullName.setText(jsonObject.getString("emri")+" "+jsonObject.getString("mbiemri"));
} catch (JSONException je) {
je.printStackTrace();
}
return convertView;
}
private class ListCell {
private TextView FullName;
}
}
and this is the error :
08-21 16:01:50.970 22616-22616/com.example.blerim.fitnesapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.blerim.fitnesapp, PID: 22616
java.lang.NullPointerException
at com.example.blerim.fitnesapp.Dieta.onCreateView(Dieta.java:45)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:942)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:482)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:17387)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:17387)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:391)
at android.view.View.measure(View.java:17387)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5352)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2533)
at android.view.View.measure(View.java:17387)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2213)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1352)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1549)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1236)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6471)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
at android.view.Choreographer.doCallbacks(Choreographer.java:603)
at android.view.Choreographer.doFrame(Choreographer.java:573)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
and this is fragment_a.xml
<FrameLayout 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:background="#FFCC00"
tools:context="com.example.blerim.fitnesapp.FragmentA">
<!-- TODO: Update blank fragment layout -->
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/android:list"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/empty"
android:layout_gravity="left|bottom" />
</FrameLayout>
************************* FINAL **************************************** Ok with the help of 2Dee now its working . FINAL WORKING CLASS :
public class Dieta extends ListFragment {
private ListView getAllPacientiListView;
private JSONArray jsonArray;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.list_fragment, container, false);
getAllPacientiListView = (ListView) v.findViewById(android.R.id.list);
new GetAllPacientiTask().execute(new ApiConnector());
return v;
}
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getAllPacientiListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
try{
//Get the pacienti which was clicked
JSONObject pacientiClicked = jsonArray.getJSONObject(position);
//Send Pacienti ID
Intent showDetails = new Intent(getActivity().getApplicationContext(),PacientiDetailsActivity.class);
showDetails.putExtra("PacientiID", pacientiClicked.getInt("pacienti_id"));
startActivity(showDetails);
}
catch(JSONException e ){
e.printStackTrace();
}
}
});
}
public void setListAdapter(JSONArray jsonArray){
this.jsonArray = jsonArray;
getAllPacientiListView.setAdapter(new GetAllPacientiListViewAdapter(jsonArray,getActivity()));
}
private class GetAllPacientiTask extends AsyncTask<ApiConnector,Long,JSONArray> {
@Override
protected JSONArray doInBackground(ApiConnector... params) {
// it is executed on Background thread
return params[0].GetAllPacienti();
}
@Override
protected void onPostExecute(JSONArray jsonArray){
setListAdapter(jsonArray);
}
}
}