简体   繁体   English

我想从数据库中获取数据并将其显示在listview上。

[英]i want to fetch a data from database and display it on listview.

xml file the first file is a xml file of the design. xml文件第一个文件是设计的xml文件。

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

    </LinearLayout>
</RelativeLayout>

rawtask.xml file this is the raw file and here design of a list view rawtask.xml文件,这是原始文件,此处是列表视图的设计

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


    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/property_display_box"
        android:id="@+id/listview1ll">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Task Name"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:textSize="30dp"
            android:id="@+id/lvtaskname" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:textSize="30dp"
            android:hint="Task Details"
            android:layout_gravity="center"
            android:id="@+id/lvtaskdetails"
            />
        <CheckBox
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Add Details"
            android:layout_marginLeft="40dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:textSize="30dp"
            android:id="@+id/lvchkbox"/>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="10dp"
            android:orientation="horizontal"
            android:id="@+id/lvl1">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                android:text="Remaining Time:"
                android:textSize="20dp"
                android:id="@+id/lvrt"/>
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Done"
                android:layout_marginLeft="90dp"
                android:layout_marginTop="10dp"
                android:textSize="20dp"
                android:id="@+id/lvdone"/>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

Listviewadapter.java the listviewadapter.java is shown Listviewadapter.java显示listviewadapter.java

public class ListViewAdapter2 extends BaseAdapter {

    Context cntx;
    AlertDialog.Builder alertDialogBuilder;
    //int loader = R.drawable.ic_menu_gallery;

    ArrayList<String> t_id=new ArrayList<String>();
    ArrayList<String> t_tname=new ArrayList<String>();
    ArrayList<String> t_detail=new ArrayList<String>();

    // ArrayList<Float> itemRating=new ArrayList<Float>();
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    //ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    /*
     * public ListViewAdapter(Context context, ArrayList<HashMap<String,
     * String>> arraylist) { this.cntx = context; data = arraylist; imageLoader
     * = new ImageLoader(context); }
     */

    public ListViewAdapter2(Context context,
                            ArrayList<String> taskid,
                            ArrayList<String> taskname,
                            ArrayList<String> taskdetail) {
        // TODO Auto-generated constructor stub
        cntx = context;
        t_id=taskid;
        t_tname = taskname;
        t_detail =taskdetail;


        //Log.d("xyz", security_id.toString());

        //ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
        //ImageLoader.getInstance().init(config);

        alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setMessage("Do You Want To Call....");
        // itemRating=itm_rating;

    }

    @Override
    public int getCount() {
        return t_id.size();
    }

    @Override
    public Object getItem(int position) {
        return t_id.get(position);
    }

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

    @SuppressWarnings("deprecation")
    public View getView(final int position, View convertView, ViewGroup parent) {

        @SuppressWarnings("unused")
        final TextView taskname, taskdetail;

        inflater = (LayoutInflater) cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LayoutInflater inflater = LayoutInflater.from(cntx);

        convertView = inflater.inflate(R.layout.rawtask, parent, false);

        /*ImageLoader imageLoader = ImageLoader.getInstance();
        DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
                .cacheOnDisc(true).resetViewBeforeLoading(true)
                .showImageForEmptyUri(loader)
                .showImageOnFail(loader)
                .showImageOnLoading(loader).build();*/

        taskname= (TextView) convertView.findViewById(R.id.lvtaskname);
        taskdetail= (TextView) convertView.findViewById(R.id.lvtaskdetails);

        taskname.setText("taskName : "+t_tname.get(position));
        taskdetail.setText("taskdetail: "+t_detail.get(position));

        return convertView;
    }

   }

main activity.java this is the final .java file of the project main activity.java,这是项目的最终.java文件

package com.example.sachin.listview;

public class Main2Activity extends Fragment {

public Main2Activity(){};
private static final String TAG_SUCCESS = "success";

JSONArray jsonarray;
JSONObject jsonobject;
ListView listview;
String img;
ListViewAdapter2 listadapter;
//ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
private static String url_task = "http://10.0.2.2/portal/aFetchtask.php";
//  private static String url_profile ="http://10.0.2.2/myapp/fetchmember.php";

JSONParser jParser = new JSONParser();

ArrayList<String> t_id = new ArrayList<String>();
ArrayList<String> t_tname = new ArrayList<String>();
ArrayList<String> t_detail = new ArrayList<String>();
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    // don't look at this layout it's just a listView to show how to handle the keyboard
    View view = inflater.inflate(R.layout.activity_main, container, false);
    getActivity().setTitle("tasks");
    new DownloadJSON().execute();
    return  view;
}


private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        //mProgressDialog = new ProgressDialog(getActivity());
        //mProgressDialog.setTitle("Please Wait");
        // Set progressdialog message
        //mProgressDialog.setMessage("Loading...");
        //mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        //mProgressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... args) {
        // Create an array
        try {
            arraylist = new ArrayList<HashMap<String, String>>();

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("abc", "abc"));
            JSONObject json = jParser.makeHttpRequest(url_task, "POST", params);

            int success1 = Integer.parseInt(json.getString(TAG_SUCCESS));
            Log.d("success", json.toString());

            if (success1 == 0) {
                Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
            }

            if (success1 == 1) {
                JSONArray ownerObj = json.getJSONArray("tasks");
                // arraylist = new ArrayList<HashMap<String, String>>();
                // Retrieve JSON Objects from the given URL address
                // Locate the array name in JSON
                // jsonarray = jsonobject.getJSONArray("images");


                for (int i = 0; i < ownerObj.length(); i++) {
                    //  HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = ownerObj.getJSONObject(i);
                    // Retrive JSON Objects

                    //securityId.add(jsonobject.getString("security_id"));
                    //   t_id.add(jsonobject.getString("t_id"));
                    t_tname.add(jsonobject.getString("t_tname"));
                    t_detail.add(jsonobject.getString("t_detail"));
                    // Number.add(jsonobject.getString("number"));

                    Log.d("DATA", jsonobject.toString());
                    //img="http://10.0.2.2/momskitchen/image/";
                    //proImage.add(img + jsonobject.getString("image"));
                             /* System.out.println(jsonobject.getString(TA));
                                System.out.println(g);*/

                }
            }
        } catch (Exception e) {
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        listview = (ListView) getActivity().findViewById(R.id.listviewtask);

        ListViewAdapter2 listadapter = new ListViewAdapter2(getActivity(), t_id, t_tname, t_detail);
        // Set the adapter to the ListView
        listview.setAdapter(listadapter);
        // Close the progressdialog

        //mProgressDialog.dismiss();
    }
}
@Override
public void onSaveInstanceState(Bundle outState) {
    //add the values which need to be saved from the drawer to the bundle
    // outState = result.saveInstanceState(outState);
    super.onSaveInstanceState(outState);
}

}

and the lastly is the file is my api file.. 最后是文件是我的api文件。

  <?php

include("connection.php");


    $response = array();    

    // get all products from products table
    $result = mysql_query("SELECT * FROM task") or die(mysql_error());

    // check for empty result
    if (mysql_num_rows($result) > 0) {
        // looping through all results
        // products node
        $response["tasks"] = array();

        while ($row = mysql_fetch_array($result))
        {

            $tasks = array();
            $tasks["t_id"] = $row["t_id"];
            $tasks["t_tname"] = $row["t_tname"];
            $tasks["t_udetail"] = $row["t_udetail"];

           // push single product into final response array
            array_push($response["tasks"], $tasks);
        }

            $response["success"] = 1;
        // echoing JSON response
        echo json_encode($response);


    }

    else 
    {
        // no products found
        $response["success"] = 0;
        $response["message"] = "No picture found";

        // echo no users JSON
        echo json_encode($response);
    }
  ?>        

here the all files are available. 这里所有文件都可用。 but the data is not fetched from the database. 但不会从数据库中获取数据。 please help me out for this.. 请为此帮我。

There are lot of coding faults are there. 那里有很多编码错误。

  • The Asynchronus class is return types are not in the exact manner to retrive the data. Asynchronus类的返回类型不是以正确的方式检索数据。
  • After protected Void doInBackground(Void... args) {} is returning null then you can get null value to onPostExcute(Void args) you have to write get whole repose in doInBackground() method only if you are not returning any response. protected Void doInBackground(Void... args) {}返回空值之后,您可以将空值传递给onPostExcute(Void args) ,只有在不返回任何响应的情况下,才必须在doInBackground()方法中编写get repose。
  • In rawtask.xml file should contains views which are inflating by adapter but in your case other view are mentioned. 在rawtask.xml文件中应包含由适配器扩展的视图,但在您的情况下,提到了其他视图。 So refere this following link to get the data from webservices into listView. 因此,请参考以下链接,将来自Web服务的数据获取到listView中。 here 这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在列表视图中显示两列。 列数据来自SQLite数据库 - how can i display two columns in listview. that columns data is coming from SQLite database 将数据库中的存储数据导入ListView。 - Getting stored data from database into ListView. 我希望Arraylist显示在列表视图中。 我该怎么做? - I want the Arraylist to display in a listview. How do I make it? 我想将用户输入的数据保存到列表视图。 我在列表视图中没有任何数据。 请突出问题 - I want to save data entered by user to listview. i am not getting any data in my listview. highlight the issue please 您好,我正在尝试将 url 中的 json 数据显示到列表视图中。 虽然什么都没有显示 - Hello i am trying to display json data from url into listview. Nothing is displayed though 如何从数据库中获取数据并将其显示在ListView上? - How to fetch a data from the database and display it on ListView? 我想从数据库中获取数据 - i want to fetch a data from the database 使用Parse.com从数据库中获取数据以显示在列表视图中 - Fetch data from database to display in a listview using Parse.com 如何从Couchbase数据库保存和获取数据并在ListView上显示? - How to save and fetch a data from the Couchbase database and display it on ListView? 返回 ListView 中被点击项目的 id。 从数据库中检索值 - Returning the id of a clicked item in a ListView. Values are retrieved from a database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM