Java 我正在使用Spinner,我想从mysql数据库中获取基于所选项目的数据,并将其放入Spinner中
/*我的代码如下。我试图在选择微调器项后从数据库中检索数据,但检索失败。请有人建议我正确的代码*/ main.xmlJava 我正在使用Spinner,我想从mysql数据库中获取基于所选项目的数据,并将其放入Spinner中,java,php,android,mysql,spinner,Java,Php,Android,Mysql,Spinner,/*我的代码如下。我试图在选择微调器项后从数据库中检索数据,但检索失败。请有人建议我正确的代码*/ main.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*"
tools:context="com.example.jay.jobfinder.MainActivity">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/logo"
android:id="@+id/ivLogo"
android:layout_span="2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tvState"
android:text="@string/tvState"
android:layout_span="2"
android:textColor="#000000"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
android:textStyle="normal|bold" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_span="2"
android:id="@+id/spinner_state" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tvJob"
android:text="@string/tvJob"
android:textColor="#000000"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
android:textStyle="normal|bold" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp">
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/rgJob">
<RadioButton
android:text="Goverment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioButton2" />
<RadioButton
android:text="Private"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioButton" />
</RadioGroup>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp">
<Button
android:text="@string/btn_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnSearch"
android:layout_span="2"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tvTag"
android:layout_span="2"
android:gravity="center_horizontal" />
</TableRow>
</TableLayout>
jobAdapter.java
package com.example.jay.jobfinder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener
{
Spinner spinner_state;
Button button;
String city,job;
TextView textView;
RadioGroup rg;
RadioButton rb;
private session session;
int rbId;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new session(getApplicationContext());
button=(Button)findViewById(R.id.btnSearch);
textView=(TextView)findViewById(R.id.tvTag);
textView.setText(city);
rg=(RadioGroup)findViewById(R.id.rgJob);
spinner_state=(Spinner)findViewById(R.id.spinner_state);
spinner_state.setOnItemSelectedListener(this);
final List<String> state = new ArrayList<String>();
state.add("Andhra Pradesh");
state.add("Arunachal Pradesh");
state.add("Assam");
state.add("Bihar");
state.add("Chandigath");
state.add("Chhattisgath");
state.add("Delhi");
state.add("Goa");
state.add("Gujarat");
state.add("Haryana");
state.add("Himachal Pradesh");
state.add("Jharkhand");
state.add("Jammu and Kashmir");
state.add("Karnataka");
state.add("Kerala");
state.add("Madhya Pradesh");
state.add("Maharashtra");
state.add("Manipur");
state.add("Meghalaya");
state.add("Mizoram");
state.add("Nagaland");
state.add("Odisha");
state.add("Puducherry");
state.add("Punjab");
state.add("Rajashtan");
state.add("Sikkim");
state.add("Tamil Nadu");
state.add("Telangana");
state.add("Tripura");
state.add("Uttar Pradesh");
state.add("Uttarkhand");
state.add("West Bengal");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,state);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_state.setAdapter(dataAdapter);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
city=spinner_state.getSelectedItem().toString();
session.setState(city);
rbId=rg.getCheckedRadioButtonId();
rb=(RadioButton)findViewById(rbId);
Toast.makeText(getApplicationContext(),"True",Toast.LENGTH_LONG).show();
/*Intent i = new Intent(MainActivity.this, JobActivity.class);
i.putExtra("data", rb.getText());
startActivity(i);*/
}
});
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
//city = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent)
{
}
}
package com.example.jay.jobfinder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Locale;
public class JobActivity extends AppCompatActivity
{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
jobAdapter adapter;
ListView listJob;
ArrayList<job> records;
private session session;
String s,states;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job);
session = new session(getApplicationContext());
states=session.getState();
Intent i = getIntent();
i.getExtras();
s = i.getStringExtra("data");
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
context=this;
records=new ArrayList<job>();
listJob=(ListView)findViewById(R.id.lvJob);
adapter=new jobAdapter(context,R.layout.list_job,R.id.tvState1,records);
listJob.setAdapter(adapter);
BackTask bt=new BackTask();
bt.execute();
}
public void onStart(){
super.onStart();
//execute background task
BackTask bt=new BackTask();
bt.execute();
}
private class BackTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(context);
//pd.setTitle("Retrieving data");
//pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
//pd.show();
}
protected Void doInBackground(Void...params)
{
InputStream is=null;
String result="";
try
{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/JobFinder/Android/FetchJob2.php");
response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
}
catch(Exception e)
{
if(pd!=null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("ERROR", "Error converting result "+e.toString());
}
//parse json data
try{
// Remove unexpected characters that might be added to beginning of the string
result=result.substring(result.indexOf("["));
JSONArray jArray =new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data =jArray.getJSONObject(i);
job p=new job();
p.setState(json_data.getString("state"));
p.setCat(json_data.getString("category"));
p.setPost(json_data.getString("post"));
p.setVacancy(json_data.getInt("vacancy"));
records.add(p);
}
}
catch(Exception e)
{
Log.e("ERROR", "Error pasting data "+e.toString());
}
return null;
}
protected void onPostExecute(Void result)
{
session.setState(s);
if(pd!=null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
adapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
@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();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
}
package com.example.jay.jobfinder;
/**
* Created by Jay on 7/13/2017.
*/
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class session
{
private SharedPreferences prefs;
public session(Context cntx)
{
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setState(String state)
{
prefs.edit().putString("state", state).commit();
// prefsCommit();
}
public String getState()
{
String state = prefs.getString("state","");
return state;
}
}
package com.example.jay.jobfinder;
/**
* Created by Jay on 7/13/2017.
*/
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
public class jobAdapter extends ArrayAdapter<job>
{
int groupid;
private ArrayList<job> originalList;
private ArrayList<job> countryList;
private JobFilter filter;
Context context;
public jobAdapter(Context context, int vg, int id, ArrayList<job> countryList)
{
super(context, vg, id, countryList);
this.context = context;
groupid = vg;
this.countryList = countryList;
this.countryList.addAll(countryList);
this.originalList = countryList;
this.originalList.addAll(countryList);
}
@Override
public Filter getFilter()
{
if (filter == null)
{
filter = new JobFilter();
}
return filter;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(groupid, parent, false);
TextView State = (TextView) itemView.findViewById(R.id.tvState1);
State.setText(countryList.get(position).getState());
TextView Category = (TextView) itemView.findViewById(R.id.tvCat1);
Category.setText(countryList.get(position).getCat() + "");
TextView Post = (TextView) itemView.findViewById(R.id.tvPost1);
Post.setText(countryList.get(position).getPost() + "");
TextView Vacancy = (TextView) itemView.findViewById(R.id.tvVac1);
Vacancy.setText(countryList.get(position).getVacancy() + "");
return itemView;
}
private class JobFilter extends Filter
{
@Override
protected Filter.FilterResults performFiltering(CharSequence constraint)
{
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<job> filteredItems = new ArrayList<job>();
for(int i = 0, l = originalList.size(); i < l; i++)
{
job area = originalList.get(i);
if(area.toString().toLowerCase().contains(constraint))
filteredItems.add(area);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint,FilterResults results)
{
countryList = (ArrayList<job>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
add(countryList.get(i));
notifyDataSetInvalidated();
}
}
}
package com.example.jay.jobfinder;
/**
* Created by Jay on 7/13/2017.
*/
public class job
{
String state,cat,post;
int vacancy;
public String getState()
{
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCat()
{
return cat;
}
public void setCat(String cat) {
this.cat = cat;
}
public String getPost()
{
return post;
}
public void setPost(String post) {
this.post = post;
}
public int getVacancy()
{
return vacancy;
}
public void setVacancy(int vacancy)
{
this.vacancy=vacancy;
}
public String toString()
{
return state + "," + cat + ","+ post+","+vacancy;
}
}
FetchJob2.php
<?php
session_start();
$city=$_POST['states'];
$con = mysql_connect("localhost","root");
mysql_select_db("jobs", $con);
$sql = "select state,category,post,vacancy from main_tbl where state='".$city."'";
// Execute query
$result = mysql_query($sql,$con);
// Loop through each records
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output));
?>
发生了什么事?如果它崩溃了,请添加您的日志,您的问题不清楚谢谢,但我的问题解决了