我想将我的应用活动代码更改为片段

时间:2018-09-17 05:21:31

标签: android fragment listactivity

我有一个具有动态列表视图的工作活动代码,我需要帮助才能更改为片段。我已经附加了Java代码,xml布局和php文件,但是我认为更改只会影响java文件。

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ViewAllCoursesActivity extends ListActivity {

SimpleAdapter adapter;

EditText inputSearch;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> coursesList;

// url to get all courses list
private static String url_all_incidents = "http://10.0.2.2/M-INFO/get_all_courses.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_COURSES = "courses";
private static final String TAG_CID = "cid";
private static final String TAG_SCHOOL = "school";
private static final String TAG_COURSE = "course";

// courses JSONArray
JSONArray courses = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_courses);

    // Hashmap for ListView
    coursesList = new ArrayList<HashMap<String, String>>();

    // Loading courses in Background Thread
    new LoadAllCourses().execute();

    // Get listview
    ListView lv = getListView();

    // on selecting single course
    // launching Edit course Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String cid = ((TextView) view.findViewById(R.id.cid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    ViewCoursesActivity.class);
            //finish();
            // sending cid to next activity
            in.putExtra(TAG_CID, cid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

// Response from Edit course Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received 
        // means user edited/deleted course
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all course by making HTTP Request
 * */
class LoadAllCourses extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ViewAllCoursesActivity.this);
        pDialog.setMessage("Loading courses. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All courses from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_incidents, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Courses: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // courses found
                // Getting Array of Courses
                courses = json.getJSONArray(TAG_COURSES);

                // looping through All Courses
                for (int i = 0; i < courses.length(); i++) {
                    JSONObject c = courses.getJSONObject(i);

                    // Storing each json item in variable
                    String cid = c.optString(TAG_CID);
                    String location = c.optString(TAG_SCHOOL);
                    String course = c.optString(TAG_COURSE);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_CID, cid);
                    map.put(TAG_SCHOOL, location);
                    map.put(TAG_COURSE, course);

                    // adding HashList to ArrayList
                    coursesList.add(map);
                }
            } else {
                // no courses found
                // Launch Add New course Activity
                Intent i = new Intent(getApplicationContext(),
                        NewCourseActivity.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all courses
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                adapter = new SimpleAdapter(
                        ViewAllCoursesActivity.this, coursesList,
                        R.layout.list_course, new String[] { TAG_CID,
                                TAG_COURSE, TAG_SCHOOL},
                        new int[] { R.id.cid, R.id.course, R.id.school });
                // updating listview
                setListAdapter(adapter);
                /**
                 * Enabling Search Filter
                 * */
                inputSearch = (EditText) findViewById(R.id.inputSearch);

                inputSearch.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                        // When user changed the Text
                        ViewAllCoursesActivity.this.adapter.getFilter().filter(cs);
                    }

                    @Override
                    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                            int arg3) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void afterTextChanged(Editable arg0) {
                        // TODO Auto-generated method stub  
                    }
                });

            }
        });
    }

}

该代码的XML list_course文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
    <TextView
        android:id="@+id/cid"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />


    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <!-- Name Label -->

    <TextView
        android:id="@+id/course"
        android:layout_width="205dp"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="16sp" />

    <!-- Name Label -->

    <TextView
        android:id="@+id/school"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:textSize="16sp" />

    </LinearLayout>

</LinearLayout>

该代码的XML all_courses文件:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">

<LinearLayout

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <!-- Main ListView Always give id value as list(@android:id/list) -->

    <!-- Search Bar -->
    <EditText
        android:id="@+id/inputSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:ems="10"
        android:maxLines="1"
        android:drawableLeft="@android:drawable/ic_menu_search" 
        android:hint="Search" >
        <requestFocus />
    </EditText>

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <!-- Name Label -->

    <TextView
        android:id="@+id/title1"
        android:layout_width="205dp"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:text="Courses"
        android:textColor="#FF0000" />

    <!-- Name Label -->

    <TextView
        android:id="@+id/title2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="6dip"
        android:paddingTop="6dip"
        android:text="School"
        android:textColor="#FF0000" />

    </LinearLayout>


    -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

</ScrollView>

用于从mysql DB中获取记录的PHP文件。

<?php

/*
 * Following code will list all the courses
 */

// array for JSON response
$response = array();


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all courses from courses table
$result = mysql_query("SELECT * FROM courses ORDER BY course ASC") or die(mysql_error());

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

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $course = array();
        $course["cid"] = $row["cid"];
        $course["school"] = $row["school"];
        $course["dept"] = $row["dept"];
        $course["course"] = $row["course"];
        $course["details"] = $row["details"];
        $course["created_at"] = $row["created_at"];


        // push single courses into final response array
        array_push($response["courses"], $course);
    }
    // successadmin
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no courses found
    $response["success"] = 0;
    $response["message"] = "No courses found";

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

2 个答案:

答案 0 :(得分:0)

查看此答案。

Convert Activity to Fragment

确保布局xml文件中的列表视图ID为

android:id="@+id/list"

不是

android:id="@android:id/list"

所有您需要做的就是将onCreate方法更改为onCreateView方法并为布局文件充气。片段中的inflate方法返回一种View类型。使用此视图变量可以识别布局中的小部件和布局。

您的onCreate方法将对此进行更改

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_courses);
    ListView lv = findViewById(R.id.list);
}

对此

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.all_courses, container, false);
    ListView lv = view.findViewById(R.id.list);
}

还要确保您具有上下文,以便可以调用诸如startActivity()之类的方法。

这是创建上下文的最佳方法之一。

创建一个这样的上下文实例变量。

Context mContext;

然后重写这样的片段的onAttach方法。

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    mContext = context;
}

所以这样的代码

startActivityForResult(in, 100);

将对此进行更改

mContext.startActivityForResult(in, 100);

希望有帮助

答案 1 :(得分:0)

我希望这将对以后的人有所帮助,并为发布大量的代码感到抱歉:

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ViewAllCoursesFragment extends Fragment {

    SimpleAdapter adapter;

    EditText inputSearch;

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> coursesList;

    // url to get all courses list
    private static String url_all_incidents = "http://10.0.2.2/M-INFO/get_all_courses.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_COURSES = "courses";
    private static final String TAG_CID = "cid";
    private static final String TAG_SCHOOL = "school";
    private static final String TAG_COURSE = "course";

    // courses JSONArray
    JSONArray courses = null;
    ListView lv;


    // Response from Edit course Activity
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted course
            // reload this screen again
            Intent intent = getActivity().getIntent();
            getActivity().finish();
            startActivity(intent);
        }

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.all_courses, container, false);

        coursesList = new ArrayList<HashMap<String, String>>();

        // Loading courses in Background Thread
        new LoadAllCourses().execute();

        // Get listview
        lv = view.findViewById(R.id.list);
        inputSearch = (EditText) view.findViewById(R.id.inputSearch);
        // on selecting single course
        // launching Edit course Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // getting values from selected ListItem
                String cid = ((TextView) view.findViewById(R.id.cid)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getActivity(),
                        MainActivity.class);
                //finish();
                // sending cid to next activity
                in.putExtra(TAG_CID, cid);

                // starting new activity and expecting some response back
                startActivityForResult(in, 100);
            }
        });
        return view;
    }

    /**
     * Background Async Task to Load all course by making HTTP Request
     */
    class LoadAllCourses extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getContext());
            pDialog.setMessage("Loading courses. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All courses from url
         */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_incidents, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Courses: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // courses found
                    // Getting Array of Courses
                    courses = json.getJSONArray(TAG_COURSES);

                    // looping through All Courses
                    for (int i = 0; i < courses.length(); i++) {
                        JSONObject c = courses.getJSONObject(i);

                        // Storing each json item in variable
                        String cid = c.optString(TAG_CID);
                        String location = c.optString(TAG_SCHOOL);
                        String course = c.optString(TAG_COURSE);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_CID, cid);
                        map.put(TAG_SCHOOL, location);
                        map.put(TAG_COURSE, course);

                        // adding HashList to ArrayList
                        coursesList.add(map);
                    }
                } else {
                    // no courses found
                    // Launch Add New course Activity
                    Intent i = new Intent(getActivity(),
                            MainActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all courses
            pDialog.dismiss();
            // updating UI from Background Thread
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    adapter = new SimpleAdapter(
                            getActivity(), coursesList,
                            R.layout.list_course, new String[]{TAG_CID,
                            TAG_COURSE, TAG_SCHOOL},
                            new int[]{R.id.cid, R.id.course, R.id.school});
                    // updating listview
                    //   setListAdapter(adapter);
                    lv.setAdapter(adapter);
                    /**
                     * Enabling Search Filter
                     * */


                    inputSearch.addTextChangedListener(new TextWatcher() {

                        @Override
                        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                            // When user changed the Text
                            ViewAllCoursesFragment.this.adapter.getFilter().filter(cs);
                        }

                        @Override
                        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                                      int arg3) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void afterTextChanged(Editable arg0) {
                            // TODO Auto-generated method stub
                        }
                    });

                }
            });
        }

    }