Android 我想将我的应用程序活动代码更改为片段
我有一个带有动态listview的活动代码,我需要帮助才能将其更改为片段。我已经附上了java代码、xml布局和php文件,但是我认为更改只会影响java文件Android 我想将我的应用程序活动代码更改为片段,android,fragment,listactivity,Android,Fragment,Listactivity,我有一个带有动态listview的活动代码,我需要帮助才能将其更改为片段。我已经附上了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.t
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
}
});
}
});
}
}
导入android.app.ListActivity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.text.Editable;
导入android.text.TextWatcher;
导入android.util.Log;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.EditText;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.TextView;
导入org.apache.http.NameValuePair;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
公共类ViewAllCoursesActivity扩展了ListActivity{
SimpleAdapter适配器;
编辑文本输入搜索;
//进度对话框
私人对话;
//创建JSON解析器对象
JSONParser jParser=新的JSONParser();
ArrayList课程列表;
//获取所有课程列表的url
私有静态字符串url\u all\u事件=”http://10.0.2.2/M-INFO/get_all_courses.php";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串TAG_COURSES=“COURSES”;
私有静态最终字符串标记_CID=“CID”;
私有静态最终字符串TAG_SCHOOL=“SCHOOL”;
私有静态最终字符串标记\u COURSE=“COURSE”;
//杰索纳雷酒店
JSONArray课程=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(右布局,所有课程);
//ListView的Hashmap
coursesList=newarraylist();
//在后台线程中加载课程
新建LoadAllCourses().execute();
//获取列表视图
ListView lv=getListView();
//论单选课
//启动“编辑课程”屏幕
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
//从选定的ListItem获取值
字符串cid=((TextView)view.findViewById(R.id.cid)).getText()
.toString();
//开始新的意图
Intent in=新的Intent(getApplicationContext(),
ViewCoursesActivity.class);
//完成();
//将cid发送到下一个活动
in.putExtra(标记CID,CID);
//开始新的活动并期望得到一些响应
startActivityForResult(in,100);
}
});
}
//编辑课程活动的回应
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
//如果结果代码为100
如果(结果代码==100){
//如果收到结果代码100
//指用户编辑/删除的课程
//重新加载此屏幕
Intent=getIntent();
完成();
星触觉(意向);
}
}
/**
*通过发出HTTP请求加载所有课程的后台异步任务
* */
类LoadAllCourses扩展异步任务{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=新建进度对话框(查看所有课程活动。此对话框);
pDialog.setMessage(“正在加载课程,请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
/**
*从url获取所有课程
* */
受保护的字符串doInBackground(字符串…args){
//建筑参数
List params=new ArrayList();
//从URL获取JSON字符串
JSONObject json=jParser.makeHttpRequest(url_all_事件,“GET”,参数);
//检查日志cat中的JSON响应
Log.d(“所有课程:,json.toString());
试一试{
//检查成功标签
int success=json.getInt(TAG_success);
如果(成功==1){
//找到的课程
//获取一系列课程
courses=json.getJSONArray(TAG_courses);
//贯穿所有课程
对于(int i=0;ivalue
地图放置(标签CID,CID);
地图放置(TAG_学校,位置);
地图放置(标记路线,路线);
//将哈希列表添加到ArrayList
课程列表。添加(地图);
}
}否则{
//找不到课程
//启动添加新课程活动
意图i=新意图(getApplicationContext(),
NewCourseActivity.class);
//关闭以前的所有活动
i、 添加标志(意图、标志、活动、清除、顶部);
星触觉(i);
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//获取所有课程后关闭对话框
pDialog.disclose();
//从更新UI
<?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 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>
<?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);
}
?>
android:id="@+id/list"
android:id="@android:id/list"
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);
}
Context mContext;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
startActivityForResult(in, 100);
mContext.startActivityForResult(in, 100);
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
}
});
}
});
}
}