0

I want to appear a new activity when I click on a ListItem, this is my whole code:

This is the ListViewActivity's code:

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

    }
    }

and this is the code of the DetailsActivity that I want to appear when I click on the any item of the 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();
        }
    }
}

This is DetailsActivity xml code:

<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>

and finally this is the php file that match with the data base:

<?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);
}
?>

When I run my app and I click any item of the list, a new activity appears but there is no data from the DB on it.

Please help

  • What are all of your logs outputting? I suspect you aren't getting a valid response from the server and since your else for that branch is empty the activity would be blank. This code smells kind of bad and you could be running into issues with the way you implemented the AsyncTask, calling `runOnUiThread` from `doInBackground` is far from best practices and could very well be the issue (though I suspect it isn't). – CodyEngel Nov 12 '15 at 03:23
  • No logs output , yes i got nothing in the browser when i call the php file – Badreddine Makdoudi Nov 12 '15 at 03:44
  • Then I would look at what you are sending to the server because you probably are not providing the correct parameters. – CodyEngel Nov 12 '15 at 04:39

1 Answers1

1

well, The problem is your String url_int_details in DetailsActivity just the same as url_act. What can I see in your DetailsActivity is: you use GET method from the "http://10.0.2.2/Scripts/details_intervention.php". And this url is contain a listView as you said but not a detail. So how to solve this problem. You should create new_url_int_details like this:

http://10.0.2.2/Scripts/details_intervention.php?id=12

Your url has to contain your item's ID. I made something just like your idea, you can learn more from my project. This is my Detail_Activity:

public class FMovieDetailsActivity extends Activity {
ArrayList<CinemaItems> cinemaList;
String id;
TextView tvNameF;
TextView tvLengthF;
TextView tvIMDbF;
TextView tvStartF;
TextView tvDescriptionF;
TextView tvCatF;
TextView tvTrailer;
TextView tvLengthTrailer;
ListView listView;
Button btnTrailer;

private Context context;

ImageView f_imageTrailer;
ImageView f_imageView;
private static final String TAG_ID = "id";
private static final String TAG_FUTURE_MOVIE = "future_movie";
private static final String TAG_NAME_F = "movienameF";
private static final String TAG_DESCRIPTION_F = "descriptionF";
private static final String TAG_IMDB_F = "imdbF";
private static final String TAG_LENGTH_F = "lengthF";
private static final String TAG_CAT = "cat_name";
private static final String TAG_IMAGE_F = "m_imageF";
private static final String TAG_SUCCESS_F = "success";
private static final String TAG_START_F = "startdateF";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.moviedetails);
    cinemaList = new ArrayList<CinemaItems>();

    Intent i = getIntent();
    id = i.getStringExtra(TAG_ID);
    new JSONAsyncTask().execute();

    tvNameF = (TextView) findViewById(R.id.tvMovieName);
    tvLengthF = (TextView) findViewById(R.id.tvLength);
    tvIMDbF = (TextView) findViewById(R.id.tvIMdb);
    tvStartF = (TextView) findViewById(R.id.tvStartDate);
    tvDescriptionF = (TextView) findViewById(R.id.tvDescription);
    tvCatF = (TextView) findViewById(R.id.tvCategory);
    f_imageView = (ImageView) findViewById(R.id.imageMovieDetail);

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

}

class JSONAsyncTask extends AsyncTask<String, String, String> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(FMovieDetailsActivity.this);
        dialog.setMessage("Loading, please wait");
        dialog.setTitle("Connecting server");
        dialog.show();
        dialog.setCancelable(false);
    }

    @Override
    protected String doInBackground(String... urls) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(TAG_ID, id));
            Log.i("show parse id", id);
            String paramString = URLEncodedUtils.format(params, "utf-8");
            //this is your problem, You lack of this url
            String url = ServicesConfig.SERVICES_HOST + ServicesConfig.SERVICES_GET_FUTURE_DETAILS + "?"
                    + paramString;

            Log.i("show url", url);
            HttpGet httpget = new HttpGet(url);
            HttpClient httpClient = new DefaultHttpClient();
            HttpResponse respone = httpClient.execute(httpget);
            HttpEntity entity = respone.getEntity();
            return EntityUtils.toString(entity, "UTF-8");

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

    @Override
    protected void onPostExecute(String respone) {
        try {

            JSONObject jsono = new JSONObject(respone);
            int success = jsono.optInt(TAG_SUCCESS_F, 0);
            if (success == 1) {
                JSONObject jsonObject = jsono.getJSONObject(TAG_FUTURE_MOVIE);
                tvNameF.setText(jsonObject.optString(TAG_NAME_F));
                tvIMDbF.setText("IMDb: " + jsonObject.optString(TAG_IMDB_F));
                tvLengthF.setText("Duration: " + jsonObject.optString(TAG_LENGTH_F));
                tvStartF.setText("Start: " + jsonObject.optString(TAG_START_F));
                tvDescriptionF.setText(jsonObject.optString(TAG_DESCRIPTION_F));
                tvCatF.setText(jsonObject.optString(TAG_CAT));

                Picasso.with(context).load(ServicesConfig.SERVICES_HOST + jsonObject.optString(TAG_IMAGE_F)).fit()
                        .into(f_imageView);
            } else {
                Toast.makeText(getBaseContext(), "Unable to fetch data from server", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        dialog.dismiss();
    }

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case android.R.id.home:

        this.finish();
        return true;

    }
    return super.onOptionsItemSelected(item);
}

}

This is my php file:

<?php
$response = array();

require_once __DIR__ . '/db_connect.php';

$db = new DB_CONNECT();

if (isset($_GET["id"])) {
 $id = $_GET['id'];

 $result = mysql_query("SELECT m.*, c.cat_name FROM future_movie as m inner join category as c on m.cat_id = c.cat_id WHERE m.id = $id");
 $img = "test_cinema/images/product/";
if (!empty($result)) {

    if (mysql_num_rows($result) > 0) {

        $result = mysql_fetch_array($result);

        $movie = array();
        $movie["id"] = $result["id"];
        $movie["movienameF"] = $result["movienameF"];
        $movie["descriptionF"] = $result["descriptionF"];
        $movie["imdbF"] = $result["imdbF"];
        $movie["lengthF"] = $result["lengthF"];
        $movie["startdateF"] = $result["startdateF"];
        $movie["cat_name"] = $result["cat_name"];
        $movie["m_imageF"] = $img.$result["m_imageF"];

        $response["success"] = 1;


        $response["future_movie"] =  $movie;




        echo json_encode($response);
    } else {

        $response["success"] = 0;
        $response["message"] = "No movie found";


        echo json_encode($response);
    }
} else {

    $response["success"] = 0;
    $response["message"] = "No movie found";


    echo json_encode($response);
}} else {

$response["success"] = 0;
$response["message"] = "Required field(s) is missing";


echo json_encode($response);}?>
TranHieu
  • 914
  • 6
  • 23