我是创建安卓应用程序的初学者。我将创建一个求职应用程序,我在编辑文本字段中输入关键字,如果我按下搜索按钮,将显示相关的工作信息:
输入职位:
[_____edittext_1_____]
输入位置:
[_____edittext_2_____]
"搜索"按钮
*问题是,例如,如果我在编辑文本 1 中输入"程序员",在编辑文本 2 中输入"纽约",然后按下搜索按钮,则不会显示相关结果。相反,它只是弹出 这个主页/界面页面 . 我按下搜索按钮,它不断返回同一页面!
主要活动.java
public class MainActivity extends ActionBarActivity implements OnClickListener {
Button button;
private EditText keywordSearch;
private EditText locationSearch;
private Button jobSearchButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
//link to UI
keywordSearch=(EditText)findViewById(R.id.keywordSearch);
locationSearch=(EditText)findViewById(R.id.locationSearch);
jobSearchButton=(Button)findViewById(R.id.jobSearchButton);
jobSearchButton.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.jobSearchButton){
Intent searchIntent = new Intent(this, MainActivity.class);
//send the keyword to the next screen
searchIntent.putExtra("key",keywordSearch.getText().toString());
searchIntent.putExtra("key",locationSearch.getText().toString());
//call the screen for listing
startActivity(searchIntent);
}
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(context, FavouriteActivity.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
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
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
列表结果.java
public class ListResult extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> idiomsList;
// url to get the idiom list
private static String url_search = "http://localhost/get_json.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_POSTNAMEIOMS = "idioms";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
// products JSONArray
JSONArray idioms = null;
//search key value
public String searchkey;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_result);
Intent myIntent = getIntent();
// gets the arguments from previously created intent
searchkey = myIntent.getStringExtra("PostName");
searchkey = myIntent.getStringExtra("Location");
// Hashmap for ListView
idiomsList = new ArrayList<HashMap<String, String>>();
// Loading idioms in Background Thread
new LoadIdioms().execute();
// Get listview
ListView lv = getListView();
// on seleting single idioms
// to do something
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String iid = ((TextView) view.findViewById(R.id.id)).getText()
.toString();
}
});
}
/**
* Background Async Task to Load Idioms by making HTTP Request
* */
class LoadIdioms extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListResult.this);
pDialog.setMessage("Loading IDIOMS. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Idioms from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//value captured from previous intent
params.add(new BasicNameValuePair("PostName", searchkey));
params.add(new BasicNameValuePair("Location", searchkey));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_search, "GET", params);
// Check your log cat for JSON response
Log.d("Search idioms: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
idioms = json.getJSONArray(TAG_POSTNAMEIOMS);
// looping through All Products
for (int i = 0; i < idioms.length(); i++) {
JSONObject c = idioms.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_POSTNAME);
String entry = c.getString(TAG_LOCATION);
String meaning = c.getString(TAG_SALARY);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_POSTNAME, id);
map.put(TAG_LOCATION, entry);
map.put(TAG_SALARY, meaning);
// adding HashList to ArrayList
idiomsList.add(map);
}
} else {
// no idioms found
//do something
}
} catch (JSONException e) {
e.printStackTrace();
}
//return "success";
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the related idioms
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ListResult.this, idiomsList,
R.layout.list_view, new String[] { TAG_POSTNAME, TAG_LOCATION, TAG_SALARY},
new int[] { R.id.id, R.id.entry, R.id.meaning});
// updating listview
setListAdapter(adapter);
}
});
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
清单.xml
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FavouriteActivity"
android:label="favourite" >
</activity>
<activity
android:name=".ListResult"
android:label="@string/title_activity_list_result" >
</activity>
</application>
你正在回忆MainActivity
内部onClick
事件的MainActivity
。在这里
Intent searchIntent = new Intent(this, MainActivity.class);
通过猜测您的流程,它应该替换为
Intent searchIntent = new Intent(this, ListResult.class);
我onClick
方法中强调了您的错误。尝试,并小心。祝你好运:)
Intent searchIntent = new Intent(this, ListResult.class);
searchIntent.putExtra("PostName",keywordSearch.getText().toString());
searchIntent.putExtra("Location",locationSearch.getText().toString());