如何使用按钮搜索将搜索查询传递给另一个活动

时间:2018-05-20 06:00:45

标签: java php android

我正在开发一个用于求职的Android应用程序,这里PHP作为后端。从服务器获取作业列表并显示为卡片视图运行良好。我想要搜索位置和职位。所以如何将我的位置和职位从搜索活动传递到工作活动。

 private void searchjob() {

        final String title = jobtitle.getText().toString().trim();
        final String location = city.getSelectedItem().toString().trim();

        Intent intent = new Intent(HomeActivity.this, MainActivity.class);
        intent.putExtra(title,1);
        intent.putExtra(location,2);


        startActivity(intent);
        overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
    }

这是我的下载卡java类。

public class DownloaderCard extends AsyncTask<Void, Integer, String> {
    Context c;
    String address;
    SwipeDeck swipeDeck;
    ProgressDialog pd;
    String url = "";

    public DownloaderCard(Context c, String address, SwipeDeck swipeDeck) {
        this.c = c;
        this.address = address;
        this.swipeDeck = swipeDeck;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(c);
        pd.setTitle("Please Wait");
        pd.setMessage("Loading....");
        pd.show();
    }
    @Override
    protected String doInBackground(Void... params) {
        String data = downloadData();
        return data;
    }
    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        pd.dismiss();
        if(s!=null){
            //Toast.makeText(c, s, Toast.LENGTH_LONG).show();
            ParserCard p = new ParserCard(c, s, swipeDeck);
            p.execute();
        }else {
            Toast.makeText(c, "Unable to download data from downloader", Toast.LENGTH_LONG).show();
        }
    }
    private String downloadData(){
        InputStream is = null;
        String line = null;
        try {
            URL url = new URL(address);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            is = new BufferedInputStream(connection.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuffer sb = new StringBuffer();
            if(br != null){
                while ((line = br.readLine()) != null){
                    sb.append(line+"\n");
                }

            }else {
                return null;
            }
            return sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(is != null){
                try {
                    is.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

这是我的JobActivity。

String urlData = "https://www.joblist.php";

        final DownloaderCard dl = new DownloaderCard(MainActivity.this,urlData , cardStack);
        dl.execute();
        cardStack.setEventCallback(new SwipeDeck.SwipeEventCallback() {
            @Override
            public void cardSwipedLeft(int position) {
                // Log.i("MainActivity", "card was swiped left, position in adapter: " + position);
            }

            @Override
            public void cardSwipedRight(int position) {
                //   Log.i("MainActivity", "card was swiped right, position in adapter: " + position);
            }

            @Override
            public void cardsDepleted() {
                // Log.i("MainActivity", "no more cards");
            }

            @Override
            public void cardActionDown() {
                // Log.i(TAG, "cardActionDown");
            }

            @Override
            public void cardActionUp() {
                // Log.i, "cardActionUp");
            }

        });
        cardStack.setLeftImage(R.id.left_image);
        cardStack.setRightImage(R.id.right_image);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cardStack.swipeTopCardLeft(180);

            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cardStack.swipeTopCardRight(180);
            }
        });
    }

3 个答案:

答案 0 :(得分:1)

这是我用来向PHP服务器发送登录信息的方法。更新它以便它符合您的目的。

      public String LoginOnService(String url,String email,String pass){
                InputStream inputStream = null;
                String result = "";
                try {

                    // 1. create HttpClient
                    HttpClient httpclient = new DefaultHttpClient();

                    // 2. make POST request to the given URL
                    HttpPost httpPost = new HttpPost(url+"?email="+email+"&password="+pass);
                    // 3. Execute POST request to the given URL
                    HttpResponse httpResponse = httpclient.execute(httpPost);
                    if(httpResponse != null){
                       result = EntityUtils.toString(httpResponse.getEntity());
                    }else{
                       result = "Did not work!";
                    }
               } catch (Exception e) {
                    Log.d("InputStream", e.getLocalizedMessage());
               }

               // 11. return result
               return result;
       } 

正如您所看到的,我正在传递String,但如果您想将数据发送为JSON,您也可能会从这些评论中受益。但在第2步中只传递了一个网址HttpPost httpPost = new HttpPost(url);

 public String LoginOnService(String url,String email,String pass){
        InputStream inputStream = null;
        String result = "";
        try {

            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url+"?email="+email+"&password="+pass);

//            String json = YOUR_JSON_STRING;

            // 3. build jsonObject
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.accumulate("Email", user.getEmail());
//            jsonObject.accumulate("Password", user.getPassword());

            // 4. convert JSONObject to JSON to String
//            json = jsonObject.toString();

            // ** Alternative way to convert Person object to JSON string usin Jackson Lib
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person);

            // 5. set json to StringEntity
//            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
//            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the content
//            httpPost.setHeader("Accept", "application/json");
//            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

//             9. receive response as inputStream
//            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if(httpResponse != null)
                result = EntityUtils.toString(httpResponse.getEntity());
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        // 11. return result
        return result;
    }

答案 1 :(得分:1)

您应该使用Volley https://github.com/google/volley来拨打 Http Requests ,这会让您的工作更轻松, 这是一个例子: -

    final String url = "https://www.joblist.php?title=MyJobTitle&location=London";

// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>() 
    {
        @Override
        public void onResponse(JSONObject response) {   
                        // display response     
            Log.d("Response", response.toString());
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {            
            Log.d("Error.Response", response);
       }
    }
);

// add it to the RequestQueue   
queue.add(getRequest);

答案 2 :(得分:0)

  final String title = jobtitle.getText().toString().trim();
        final String location = city.getSelectedItem().toString().trim();

 Intent intent = new Intent(HomeActivity.this, MainActivity.class);
        intent.putExtra("job_title",title);
        intent.putExtra("city",location);
在JobActivity中

 String myvalue= getIntent().getExtras("job_title");
 String myvalue2= getIntent().getExtras("city");

php code

final String url =&#34; https://www.joblist.php?title=&#34; + myvalue +&#34;&amp; location =&#34; + myvalue2;