【问题标题】:parsing json data into listview in ListFragment将json数据解析为ListFragment中的listview
【发布时间】:2014-08-21 14:19:09
【问题描述】:

我在将 JSON 数据解析为 listFragment 时遇到问题。 我用 TabBar 试过这个,但我试图用 Fragments 修复它....

这是应该将数据放入列表视图的类:

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);
    }
    }
    }

这是 ApiConnector 类:

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;

 }

 }

这是 getAllPacientiListView 类:

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;
}

}

这是错误:

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)

这是 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>

******************************最终*********** *********************************** 在 2Dee 的帮助下,现在可以正常工作了。 最后的工作班:

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);
    }
    }
    }

【问题讨论】:

  • “我有问题” >> 哪一个?
  • 我建议您使用 Gson 解析器和自定义模型对象,这样代码会更简单、更简洁。
  • @2Dee 错误现在在帖子中。对不起
  • 似乎 pacientiClicked 为 null 或没有键 "pacienti_id" 。你能检查一下吗?
  • @SirKuryaki PacientiClicked 它的 not null im 使用这个数据库和这个代码到另一个扩展 TabActivity 的应用程序中,它在那里工作。但是当我尝试扩展到 ListFragment 时它不起作用

标签: android json database listview android-activity


【解决方案1】:

您不能在onCreateView 中调用getActivity(),因为您无法确定您的Activity 是否已完全创建(查看this answer)。

getActivity() 需要放在onActivityCreated 中,但在片段布局中包含ListView 可能是更好的解决方案,因此您可以这样做:

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

此外,您似乎在 Fragment 中夸大了 Activity 布局:

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

应该是

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

【讨论】:

  • 您的 ListView 为空,可能是因为您试图在 Activity 的布局中查找 ID 为“list”的 ListView,而不是在 Fragment 的布局中使用。
  • 它不可点击,因为您没有将点击侦听器设置为正确的 ListView。 findViewById(R.id.list) 为您获取框架包含在您的 ListFragment 中的 ListView,但您正在使用具有不同 id('android_list' 而不是'list')的 ListView 膨胀自定义布局。也许从教程开始,以更好地了解布局中带有 ListView 的 Fragment 与 ListFragment 之间的区别......这可能是一个好的开始:vogella.com/tutorials/AndroidListView/article.html#listactivity
  • 我已对其进行了编辑,因为现在它正在显示 pacientiList,但是当我尝试单击其中一个名称时,没有任何活动,感谢您的宝贵时间
  • “无活动”:甚至没有从您的 catch 子句打印的堆栈跟踪?
  • 我在帖子中添加了 PacientiDetailsActivity。不,没有任何活动,甚至连一个 stacttrace 也没有
猜你喜欢
  • 2016-03-03
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多