使用Json在MySQL数据库中进行实时搜索,并在listview android中显示结果

时间:2017-06-22 11:32:27

标签: java android mysql json

我正在使用MySQL,JSON进行实时搜索。它与本地数组值一起正常工作。但不使用MySQL。我担心的是,当用户开始输入时,必须从数据库中搜索并在listview中显示它。 bellow是我的搜索适配器

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

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

import zesteve.com.myapplication.R;
import zesteve.com.myapplication.Search;
import zesteve.com.myapplication.VendProfileActivity;

/**
 * Created by Ravi Shankar on 6/22/2017.
 */

public class SearchAdapter extends BaseAdapter {

    // Declare Variables
    Context mContext;
    LayoutInflater inflater;
    private List<Search> vendersearchlist = null;
    private ArrayList<Search> arraylist;

    public SearchAdapter(Context context,
                           List<Search> vendersearchlist) {
        mContext = context;
        this.vendersearchlist = vendersearchlist;
        inflater = LayoutInflater.from(mContext);
        this.arraylist = new ArrayList<Search>();
        this.arraylist.addAll(vendersearchlist);
    }

    public class ViewHolder {
        TextView id;
        TextView vname;
    }

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

    @Override
    public Search getItem(int position) {
        return vendersearchlist.get(position);
    }

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



    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.search_item_list, null);
            // Locate the TextViews in listview_item.xml
            //holder.id = (TextView) view.findViewById(R.id.id);
            holder.vname = (TextView) view.findViewById(R.id.autoCompleteTextView);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Set the results into TextViews
        //holder.rank.setText(Search.get(position).getRank());
        holder.vname.setText(vendersearchlist.get(position).getVname());

        // Listen for ListView Item Click
        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Send single item click data to SingleItemView Class
                Intent intent = new Intent(mContext, VendProfileActivity.class);
                // Pass all data rank
                intent.putExtra("Vend_Id",
                        (vendersearchlist.get(position).getId()));
                // Pass all data country
                intent.putExtra("Vend_Name",
                        (vendersearchlist.get(position).getVname()));
                // Pass all data population

                // Start SingleItemView Class
                mContext.startActivity(intent);
            }
        });

        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        vendersearchlist.clear();
        if (charText.length() == 0) {
            vendersearchlist.addAll(arraylist);
        } else {
            for (Search sl : arraylist) {
                if (sl.getVname().toLowerCase(Locale.getDefault())
                        .contains(charText)) {
                    vendersearchlist.add(sl);
                }
            }
        }
        notifyDataSetChanged();
    }

}

AND POJO

public class Search {
    private int id;
    private String vname;

    public Search(int id, String vname) {
        this.id = id;
        this.vname = vname;
    }

    public int getId() {
        return this.id;
    }

    public String getVname() {
        return this.vname;
    }

}

我的SearchActivity.java

import android.content.res.Resources;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import okhttp3.OkHttpClient;
import okhttp3.Response;
import zesteve.com.myapplication.adapter.SearchAdapter;
import zesteve.com.myapplication.adapter.VenderAdapter;

public class Search_vender extends AppCompatActivity {

    String  catname,city;
    int catid;

    private EditText Vendname;
    private Session session;
    ListView listview;
    SearchAdapter adapter;
    int[] id;
    String[] vname;
    ArrayList<Search> vendersearchlist = new ArrayList<Search>();

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

        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        session = new Session(Search_vender.this);

        catid = getIntent().getIntExtra("CatId",00);
        catname= getIntent().getStringExtra("CatName");
        city = session.getUserLocation().get(session.KEY_UCITY);


        listview = (ListView) findViewById(R.id.listview);
        Vendname = (EditText) findViewById(R.id.searchitem);
        Vendname.setHint("Search "+catname+" in "+city);


        //fetch data from server in json
        String vsearch = Vendname.getText().toString();
        prepareVender(vsearch);


        // Pass results to ListViewAdapter Class
        adapter = new SearchAdapter(this, vendersearchlist);

        // Binds the Adapter to the ListView
        listview.setAdapter(adapter);

        // Locate the EditText in listview_main.xml

        Vendname.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
                String text = Vendname.getText().toString().toLowerCase(Locale.getDefault());
                adapter.filter(text);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                // TODO Auto-generated method stub
            }
        });
    }

    private void prepareVender(String sText){

        AsyncTask<String,Void,Void> task = new AsyncTask<String, Void, Void>() {
            @Override
            protected Void doInBackground(String... strings) {

                OkHttpClient client = new OkHttpClient();
                okhttp3.Request request = new okhttp3.Request.Builder()
                        .url("http://api.zesteve.com/vend_list.php?city="+city+"&catid="+catid+"&name="+strings[0])
                        .build();
                try{
                    Response response = client.newCall(request).execute();
                    JSONArray array = new JSONArray(response.body().string());

                    for (int i=0; i<array.length(); i++){

                        JSONObject object= array.getJSONObject(i);

                        Search vender = new Search(object.getInt("id"),

                                object.getString("name"));

                        vendersearchlist.add(vender);
                    }

                }catch (IOException e){
                    e.printStackTrace();
                } catch (JSONException e) {
                    System.out.println("End of Catagory");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                adapter.notifyDataSetChanged();
            }
        };
        task.execute(sText);
    }


    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

}

如果您有任何疑问,请发表评论。

1 个答案:

答案 0 :(得分:0)

如果有人在寻找相同的解决方案。吼叫是我的代码

EAR

当用户统计搜索第二个字符时,它会起作用。