使用php将填充的listview项插入到android中的数据库

时间:2016-04-14 06:00:44

标签: php android mysql listview android-volley

这里我使用php文件从数据库填充listview。从数据库中取出后我想将它们添加到另一个表中..在我的 onclick of add button toast message中显示相应的名称..但是当我尝试在 uploadImage()方法中将名称添加到数据库时,只有列表视图中存在的姓氏才会插入数据库,而不管名称如何。 如何在单击时插入相应的名称。这是列表.. enter image description here

这是我的代码..

package info.androidhive.customlistviewvolley.adater;

    import info.androidhive.customlistviewvolley.R;
    import info.androidhive.customlistviewvolley.model.Movie;

    import java.util.HashMap;
    import java.util.List;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.android.volley.toolbox.ImageLoader;
    import com.android.volley.toolbox.NetworkImageView;

    public class CustomListAdapter extends BaseAdapter {
        private Activity activity;
        private LayoutInflater inflater;
        private List<Movie> movieItems;
        private Button add;
        private Movie m;
        private TextView editname;
        private TextView editurl;
        //private Button nano;

        public static final String KEY_FULL = "name";
        public static final String KEY_MOBILE = "url1";
        public static final String UPLOAD_URL = "http://oursite/micro1.php";

        public CustomListAdapter(Activity activity, List<Movie> movieItems) {
            this.activity = activity;
            this.movieItems = movieItems;
        }

        @Override
        public int getCount() {
            return movieItems.size();
        }

        @Override
        public Object getItem(int location) {
            return movieItems.get(location);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (inflater == null)
                inflater = (LayoutInflater) activity
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (convertView == null)
                convertView = inflater.inflate(R.layout.list_row, null);


            editname = (TextView) convertView.findViewById(R.id.fullname);
            editurl = (TextView) convertView.findViewById(R.id.mobile);
            add = (Button)convertView.findViewById(R.id.button);

             m = movieItems.get(position);

             editname.setText(m.getName());
             final  String  name =  m.getName();

            editurl.setText( m.getUrl());
            editurl.setVisibility(View.GONE);

            add.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Toast.makeText(v.getContext(), "Name:"+name, Toast.LENGTH_SHORT).show();// displays exact name when add button is pressed in listview.
                    //uploadImage();

                    /*Intent intent = new Intent(v.getContext(), WebViewActivity.class);
                    intent.putExtra("Url",editurl.getText().toString() );
                    activity.startActivity(intent);*/


                }
            });

            return convertView;

        }

/*** if uploadImage() method is used..only the last data present in listview is inserted..**/
        /*public  void uploadImage(){
            final  String  name = m.getName();
            final String url1 =  m.getUrl();

            class UploadImage extends AsyncTask<Void,Void,String> {
                ProgressDialog loading;
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    loading = ProgressDialog.show(activity,"Please wait...","uploading",false,false);
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    loading.dismiss();
                    if(s.equalsIgnoreCase("Successfully Stored")){
                        //Intent intent = new Intent(activity,Insurance.class);
                        Toast.makeText(activity,s,Toast.LENGTH_SHORT).show();
                        //activity.startActivity(intent);
                    }else{
                        Toast.makeText(activity,s,Toast.LENGTH_SHORT).show();

                    }
                }

                @Override
                protected String doInBackground(Void... params) {

                    //RegisterUserClass rh = new RegisterUserClass();
                    RequestHandler rh = new RequestHandler();
                    HashMap<String,String> param = new HashMap<String,String>();

                    param.put(KEY_FULL,name);
                    param.put(KEY_MOBILE,url1);

                    String result = rh.sendPostRequest(UPLOAD_URL, param);
                    return result;
                }
            }
            UploadImage u = new UploadImage();
            u.execute();
        }*/

        }

MainActivity.java

package info.androidhive.customlistviewvolley;

import info.androidhive.customlistviewvolley.adater.CustomListAdapter;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.Movie;

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

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;

public class MainActivity extends Activity {
    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Movies json url
    private static final String url = "http://oursite/dummi.php";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

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

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);
        //micro = ()

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // changing action bar color
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setName(obj.getString("name"));
                                movie.setUrl( obj.getString("url1"));

                                movieList.add(movie);

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

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hidePDialog();

                    }
                });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

micro1.php

<?php
    session_start();
    define('HOST','localhost');
    define('USER','username');
    define('PASS','password');
    define('DB','dbname');

    $response = array();

    $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

    if(!mysqli_connect_errno()){

        $error_flag = false;

        $name= $_POST['name'];
        $url1= $_POST['url1'];


            $sql = "INSERT INTO micro (name, url1,  created_at)
            VALUES ('$name', '$url1', NOW())";
                if(mysqli_query($con,$sql)){

                    echo "Successfully Stored";

                }else{
                    $response["error"] = true;
                    $response["error_msg"] = "INSERT operation failed";
                    echo json_encode($response);
                }


    }else{
        $response["error"] = true;
        $response["error_msg"] = "Database connection failed";
        echo json_encode($response);
    }
?>

0 个答案:

没有答案