У меня есть код рабочей активности с динамическим списком, который мне нужен, чтобы перейти к фрагменту. Я приложил код 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>
PHP-файл для извлечения записей из БД mysql.
<?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);
}
?>