mercredi 22 juin 2016

How to populate a listview in ndroid using PHP with volley

Hi i am having trouble trying to get my andoid app to return a list view of all search results returned from a PHP files. I am using a wamp server to host the php files then i call them in the application using Volley. My problem is i cant get it to work with multiple return values. I have tried many different ways using videos online and resources from this site but i cant seem to get to work. this is my first android application so i am new enough of the idea of a list view and json.

here is my code.

package com.example.mullally.newloginregister;

import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class HomeScreen extends AppCompatActivity {

    String status = "";
    ArrayAdapter<String> adapter;
    ArrayList<String> items;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen);

        final TextView createLink = (TextView) findViewById(R.id.tvCreate);
        final TextView lostLink = (TextView) findViewById(R.id.tvLost);
        final TextView foundLink = (TextView) findViewById(R.id.tvFound);
        final Button btTest = (Button) findViewById(R.id.btTest);

        createLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent registerIntent = new Intent(HomeScreen.this, CreateAdvert.class);
                HomeScreen.this.startActivity(registerIntent);

            }
        });

        lostLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status="Lost";
                // Response received from the server
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");

                            if (success) {
                                    String title = jsonResponse.getString("title");
                                    String location = jsonResponse.getString("location");

                                    Intent intent = new Intent(HomeScreen.this, BrowseLost.class);
                                    intent.putExtra("title", title);
                                    intent.putExtra("location", location);
                                    HomeScreen.this.startActivity(intent);


                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
                                builder.setMessage("Something Went Wrong")
                                        .setNegativeButton("Back", null)
                                        .create()
                                        .show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };

                BrowseRequest browseRequest = new BrowseRequest(status, responseListener);
                RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
                queue.add(browseRequest);
            }
        });

        foundLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status = "Found";
                // Response received from the server
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                            try {
                                JSONObject jsonResponse = new JSONObject(response);
                                boolean success = jsonResponse.getBoolean("success");

                                if (success) {
                                    String title = jsonResponse.getString("title");
                                    String location = jsonResponse.getString("location");

                                    Intent intent = new Intent(HomeScreen.this, BrowseFound.class);
                                    intent.putExtra("title", title);
                                    intent.putExtra("location", location);
                                    HomeScreen.this.startActivity(intent);


                                } else {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
                                    builder.setMessage("Something Went Wrong")
                                            .setNegativeButton("Back", null)
                                            .create()
                                            .show();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                };

                BrowseRequest browseRequest = new BrowseRequest(status, responseListener);
                RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
                queue.add(browseRequest);
            }
        });


        btTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status = "Found";
                // Response received from the server
                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {


                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");

                            if (success) {
                                String title = jsonResponse.getString("title");
                                String description = jsonResponse.getString("description");
                                String location = jsonResponse.getString("location");
                                String status = jsonResponse.getString("status");
                                String category = jsonResponse.getString("category");

                                Intent intent = new Intent(HomeScreen.this, ViewAdvert.class);
                                intent.putExtra("title", title);
                                intent.putExtra("description", description);
                                intent.putExtra("location", location);
                                intent.putExtra("status", status);
                                intent.putExtra("category", category);
                                HomeScreen.this.startActivity(intent);


                            } else {
                                AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
                                builder.setMessage("Something Went Wrong")
                                        .setNegativeButton("Back", null)
                                        .create()
                                        .show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };

                ViewRequest viewRequest = new ViewRequest(status, responseListener);
                RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
                queue.add(viewRequest);
            }
        });

this is the home screen when a textview is clicked it would launch a request using volley in a seperate request class it is supposed to then return values add them to a json response opject and pass them into the Browse Lost class where it is then added to a listView.

This is the Request class:

package com.example.mullally.newloginregister;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by mullally on 14/04/2016.
 */
public class BrowseRequest extends StringRequest {
                                                            //192.168.11.2
    private static final String  BROWSE_REQUEST_URL = "http://192.168.11.5/android_content/GetAdvert.php";
    private Map<String,String> params;

    public BrowseRequest(String status, Response.Listener<String> listener){
        super(Request.Method.POST, BROWSE_REQUEST_URL,listener, null);
        params=new HashMap<>();
        params.put("status", status);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }


}

and this is the activity that is launched to display the list :

package com.example.mullally.newloginregister;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

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

public class BrowseLost extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browse_lost);


        final ListView listView = (ListView) findViewById(R.id.listView);

        final Intent intent= getIntent();
        String title = intent.getStringExtra("title");
        String location = intent.getStringExtra("location");

        String details = title + "          Location: " + location;

        List<String> foundArray = new ArrayList<>();
        foundArray.add(details);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_activated_2, android.R.id.text1, foundArray);


        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item index
                int itemPosition     = position;

                // ListView Clicked item value
                String  itemValue    = (String) listView.getItemAtPosition(position);

                // Show Alert
                Toast.makeText(getApplicationContext(),
                        "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG)
                        .show();

            }

        });

    }
}

so basically i am trying to populate the listview with all values returned from the PHP , the php encodes the values into a json response eg.

[{"title":"Phone Found","location":"Dublin 6"},{"title":"test","location":"Dublin"},{"title":"dog","location":"Dublin 1"},{"title":"new","location":"Dublin 6W"}]

Aucun commentaire:

Enregistrer un commentaire