0

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);
    }
    }
    }
7
  • "I have a problem " >> which one ? Commented Aug 21, 2014 at 14:22
  • 1
    I suggest you use the Gson parser and a custom model object it will be much easier and cleaner code. Commented Aug 21, 2014 at 14:22
  • @2Dee the error now its in the post. sorry Commented Aug 21, 2014 at 14:24
  • It seems that pacientiClicked is null or doesn't have the key "pacienti_id" . Could you check that? Commented Aug 21, 2014 at 14:28
  • @SirKuryaki PacientiClicked its not null im using this database and this code into another app that extends TabActivity and there it works. but its not working when im trying to extend into ListFragment Commented Aug 21, 2014 at 14:32

1 Answer 1

1

You cannot call getActivity() inside onCreateView as you cannot be sure your Activity is fully created at that point (have a look at this answer).

getActivity() need to be placed inside onActivityCreated, but including the ListView in your Fragment's layout is probably a much better solution, so you could do something like this :

View v = inflater.inflate(R.layout.activity_list, container, false);
getAllPacientiListView = (ListView) v.findViewById(R.id.list);

Also, it looks like you're inflating your Activity layout in the Fragment :

View v = inflater.inflate(R.layout.activity_list, container, false);

should be

View v = inflater.inflate(R.layout.your_fragment_layout, container, false);
Sign up to request clarification or add additional context in comments.

5 Comments

Your ListView is null, probably because you are trying to look for a ListView with id 'list' in your Activity's layout instead of using the one in the Fragment's layout.
It is not clickable because you are not setting the click listener to the correct ListView. findViewById(R.id.list) gets you the ListView included in your ListFragment by the framework, but you are inflating a custom layout with a ListView which has a different id ('android_list' instead of 'list'). Perhaps start with tutorials to better understand the difference between a Fragment with a ListView in it's layout and the ListFragment... This could be a good start : vogella.com/tutorials/AndroidListView/article.html#listactivity
i have edited that because now its working to show the pacientiList but when i try to click one of the names there there is no activity, and thank you for your time
"no activity" : not even a stacktrace printed from your catch clause ?
i have added the PacientiDetailsActivity in post. no there is no activity not even a stactrace

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.