gpt4 book ai didi

java - 使用 Json 实时搜索 MySQL 数据库并在 ListView android 中显示结果

转载 作者:行者123 更新时间:2023-11-29 18:45:21 25 4
gpt4 key购买 nike

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

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

}

和 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;
}

}

如有疑问请评论。

最佳答案

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

public class Search_vender extends AppCompatActivity {

String catname,city;
int catid;

SearchView Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
ArrayList<Search> filteredSearchResults = new ArrayList<Search>();
ProgressDialog progressDialog;

@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);

progressDialog = new ProgressDialog(Search_vender.this);
progressDialog.setCancelable(false);

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

//Toast.makeText(Search_vender.this,catid + city,Toast.LENGTH_LONG).show();
listview = (ListView) findViewById(R.id.listview);
Vendname = (SearchView) findViewById(R.id.searchitem);
Vendname.setQueryHint("Search "+catname+" in "+city);




Vendname.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub

//Toast.makeText(Search_vender.this, String.valueOf(hasFocus),Toast.LENGTH_SHORT).show();
}
});

Vendname.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub

return false;
}

@Override
public boolean onQueryTextChange(String newText) {

if(newText.length() > 2){

listview.setVisibility(View.VISIBLE);
GetDataVender gv = (GetDataVender) new GetDataVender().execute(newText);
}else{

listview.setVisibility(View.INVISIBLE);
}

return false;
}
});

}

public void filterSearchArray(String newText){
String pName;

filteredSearchResults.clear();
for (int i = 0; i < vendersearchlist.size(); i++)
{
pName = vendersearchlist.get(i).getVname().toLowerCase();
if ( pName.contains(newText.toLowerCase()))
{
filteredSearchResults.add(vendersearchlist.get(i));
}
}
}


class GetDataVender extends AsyncTask<String, Void, String>{
String textsearch;

@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading Please Wait...");
showDialog();
}

@Override
protected String doInBackground(String... strings) {

OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/autosearch.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
this.textsearch = strings[0];
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 catagory = new Search(object.getInt("id"),
object.getString("name"));

vendersearchlist.add(catagory);
}

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

return null;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

if(result != null && result.equalsIgnoreCase("Exception Caught")){
Toast.makeText(Search_vender.this, "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
hideDialog();
}else{

filterSearchArray(textsearch);
listview.setAdapter(new SearchAdapter(Search_vender.this,filteredSearchResults));
hideDialog();
}

//hideDialog();
//adapter.notifyDataSetChanged();
}
}

private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}

private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}

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

}

当用户从第二个字符开始进行统计搜索时,它会起作用。

关于java - 使用 Json 实时搜索 MySQL 数据库并在 ListView android 中显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44698217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com