Я хочу, чтобы появиться новый вид деятельности, когда я нажимаю на ListItem, это весь мой код:OnItemClick из ListView
Это код в ListViewActivity в:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import json.JSONParser;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class IntervActivity extends ListActivity implements OnItemClickListener
{
//private static final String TAG_PID = "ID";
private static final String TAG_NAME = "name";
ArrayList<HashMap<String, String>> actList;
private ProgressDialog progressMessage;
private static String url_act= "http://10.0.2.2/Scripts/liste_interventions.php";
//private static String url_act= "http://192.168.43.95/android_Web_Service/actualite.php";
JSONParser jParser = new JSONParser();
JSONArray act = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.interv_list);
actList = new ArrayList<HashMap<String, String>>();
new LoadAllact().execute();
// Get listview
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name= ((TextView) view.findViewById(R.id.name)).getText().toString();
// Starting new intent
Intent in = new Intent(IntervActivity.this,
DetailsActivity.class);
// sending pid to next activity
in.putExtra(TAG_NAME, name);
startActivity(in);
}
});
}
class LoadAllact extends AsyncTask<String,String,String>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
progressMessage = new ProgressDialog(IntervActivity.this);
progressMessage.setMessage("chargement actualité...");
progressMessage.setIndeterminate(false);
progressMessage.setCancelable(false);
progressMessage.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_act, "GET", params);
Log.d("actualite: ", json.toString());
try {
int success = json.getInt("success");
if (success == 1)
{
act = json.getJSONArray("act");
for (int i = 0; i < act.length(); i++)
{
JSONObject c = act.getJSONObject(i);
// String id = c.getString("id");
String name = c.getString("name");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
//map.put("Int_id", id);
map.put("Int_name", name);
actList.add(map);
}
}
} catch (JSONException e) {e.printStackTrace();}
return null;
}
protected void onPostExecute(String file_url)
{
progressMessage.dismiss();
runOnUiThread(new Runnable()
{
public void run() {
ListAdapter adapter = new SimpleAdapter(
IntervActivity.this, actList,
R.layout.interv_list_item, new String[] {"Int_name"},
new int[]{ R.id.name });
setListAdapter(adapter);
}
});
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
и это код DetailsActivity, что я хочу, чтобы появиться, когда я нажимаю на любом из пунктов ListView:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import json.JSONParser;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class DetailsActivity extends Activity {
private static final String TAG_NAME = "name";
public String name;
private static final String TAG_SUCCESS = "success";
ArrayList<HashMap<String, String>> actList;
private ProgressDialog pDialog;
private static String url_int_details= "http://10.0.2.2/Scripts/details_intervention.php";
//private static String url_act= "http://192.168.43.95/android_Web_Service/actualite.php";
JSONParser jParser = new JSONParser();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_activity);
Intent i = getIntent();
// getting product id (pid) from intent
String name = i.getStringExtra("name");
// Getting complete product details in background thread
new GetProductDetails().execute();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DetailsActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jParser.makeHttpRequest(
url_int_details, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray("interv"); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
TextView tvLibelle = (TextView)
findViewById(R.id.textView1);
tvLibelle.setText(product.getString("name"));
TextView tvDate= (TextView)
findViewById(R.id.textView2);
tvDate.setText(product.getString("date"));
TextView tvEchéance= (TextView)
findViewById(R.id.textView3);
tvEchéance.setText(product.getString("date_deadline"));
TextView tvPriorité= (TextView)
findViewById(R.id.textView4);
tvPriorité.setText(product.getString("priority"));
TextView tvDescription= (TextView)
findViewById(R.id.textView5);
tvDescription.setText(product.getString("description"));
TextView tvEtat= (TextView)
findViewById(R.id.textView6);
tvEtat.setText(product.getString("state"));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
Это DetailsActivity код XML:
<RelativeLayout 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:gravity="top"
android:background="#99E7E5"
tools:context="com.example.mobisav.DetailsActivity" >
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView4"
android:layout_alignBottom="@+id/textView4"
android:layout_alignRight="@+id/textView2"
android:hint="@string/Etat"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="36dp"
android:hint="@string/Echeance"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/textView5"
android:hint="@string/Nom_intervention" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_centerVertical="true"
android:hint="@string/Priority"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignLeft="@+id/textView6"
android:layout_marginBottom="33dp"
android:hint="@string/Description"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="28dp"
android:hint="@string/Date"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="14dp"
android:layout_toLeftOf="@+id/textView4"
android:hint="@string/Appeler" />
</RelativeLayout>
и, наконец, это файл PHP, который совпадает с базой данных:
<?php
// array for JSON response
$response = array();
$hostname_localhost ='localhost';
$port_localhost =5432;
$database_localhost ='techmobi';
$username_localhost ='openpg';
$password_localhost ='openpgpwd';
$localhost = "host='$hostname_localhost' port='$port_localhost' dbname='$database_localhost' user='$username_localhost' password='$password_localhost'";
// check for post data
$connexion =pg_connect($localhost) or die ("Erreur de connexion ".pg_last_error());
if (isset($_GET["name"])) {
$name = $_GET["name"];
$query_search = "SELECT id, name, date, priority, state, description, date_deadline FROM crm_helpdesk WHERE name = $name";
$query_exec = pg_query($query_search) or die(pg_error());
if (!empty($query_exec)) {
// check for empty result
if (pg_num_rows($result) > 0) {
$query_exec = pg_fetch_array($query_exec);
$interv = array();
$interv["id"] = $query_exec ["id"];
$interv["name"] = $query_exec ["name"];
$interv["date"] = $query_exec ["date"];
$interv["description"] = $query_exec ["description"];
$interv["priority"] = $query_exec ["priority"];
$interv["state"] = $query_exec ["state"];
$interv["date_deadline"] = $query_exec ["date_deadline"];
// success
$response["success"] = 1;
// user node
$response["interv"] = array();
array_push($response["interv"], $interv);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Когда я запускаю мое приложение, и я нажимаю любой элемент списка, появляется новый вид деятельности, но нет никаких данных от БД на нем.
Пожалуйста, помогите
Что все ваши журналы выводя? Я подозреваю, что вы не получаете действительного ответа от сервера, и поскольку ваше другое для этого филиала пустое, активность будет пустой. Этот код плохо пахнет, и вы можете столкнуться с проблемами, связанными с тем, как вы реализовали AsyncTask, вызов 'runOnUiThread' из' doInBackground' далек от передового опыта и вполне может быть проблемой (хотя я подозреваю, что это isn ' т). – CodyEngel
Нет вывода журналов, да, я ничего не получил в браузере, когда вызываю php-файл –
. Тогда я бы посмотрел, что вы отправляете на сервер, потому что вы, вероятно, не предоставляете правильные параметры. – CodyEngel