如何使用保存选择并应用于API的微调器来过滤选项? - ANDROID

时间:2014-04-03 06:55:37

标签: android spinner

我很难找到答案,因为涉及很多因素。我制作了一个简单的搜索引擎应用程序,它使用微调器为搜索选择过滤选项,例如:您可以选择要搜索的图像的颜色或大小。我在他们的API(JSON格式)中使用Google搜索API和搜索参数。这是开发人员链接(显示我必须使用的参数名称):https://developers.google.com/imagesearch/v1/jsondevguide#request_format

问题:该应用运行正常,除非您选择过滤器选项,例如红色...它实际上返回错误的过滤器,它返回蓝色。我查看了我的switch语句,在那里我按案例编号排序API参数,它们匹配我的strings.xml中的XML布局(不确定字符串顺序是否重要),以及在运行时匹配实际的下拉列表微调器顺序应用程序。我也使用getSelectedItemPosition()方法,我假设它会选择实际的过滤器,但我必须遗漏一些东西。

尽管这个项目非常复杂,但我得到了很多代码的帮助,所以我不确定它到底意味着什么(或者确实如此)......我还在学习和初学者。< / p>

我将发布我的两个主要活动,但如果你需要更多(比如我的XML),请告诉我。这两项活动很长,所以如果我不需要,也不想发帖太多。非常感谢你提前!

我的主要活动包含一个EditText字段,一个搜索按钮和一个高级搜索按钮(导致活动#2低于此一个)。

package com.noni.gridimagesearch;

import java.util.ArrayList;

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

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

public class SearchActivity extends Activity {
    EditText etQuery;
    GridView gvResults; 
    Button btnSearch;
    Button advancedSearch;
    String filterPreferences;
    private String FilterPreferences;

    ArrayList<ImageResult> imageResults = new ArrayList<ImageResult>();
    ImageResultArrayAdapter imageAdapter;


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

        setupViews();

        //This enables you to click on an image, and see it in its own activity
        imageAdapter = new ImageResultArrayAdapter(this, imageResults);
        gvResults.setAdapter(imageAdapter);
        gvResults.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapter, View parent, 
                    int position, long rowId) {
                Intent i = new Intent(getApplicationContext(), 
                        ImageDisplayActivity.class);
                ImageResult imageResult = imageResults.get(position);
                i.putExtra("result", imageResult);
                startActivity(i);
            }
        });

//      //Attempt at the endless scroll feature
//      GridView gvResults = (GridView) findViewById(R.id.gvResults);
//      gvResults.setOnScrollListener(new EndlessScrollListener() {
//          @Override
//          public void onLoadMore(int page, int totalItemsCount) {
//              loadMoreImages(totalItemsCount); 
//          }
//      });
//      
//      public void loadMoreImages(int totalItemsCount) {
//          String query = etQuery.getText().toString();
//          AsyncHttpClient client = new AsyncHttpClient();
//          makeAsyncHttpGetRequest(client, totalItemsCount, query);
//      }

        //Create intent to go from Advanced Search button to Advanced Search Activity
        Button advancedSearch = (Button) findViewById(R.id.advancedSearch);
        advancedSearch.setOnClickListener(new OnClickListener() {
            public void onClick(View v){
                Intent i = new Intent (SearchActivity.this, AdvancedOptionsActivity.class);
                startActivity(i);
            }   
        });

    }//end onCreate method

    public void setupViews() {
        etQuery = (EditText) findViewById(R.id.etQuery);
        gvResults = (GridView) findViewById(R.id.gvResults);
        btnSearch = (Button) findViewById(R.id.btnSearch);  
    }

    //Using onClick method from btnSearch in layout, called onImageSearch
    public void onImageSearch(View v) {
        String query = etQuery.getText().toString();
        Toast.makeText(this, "Searching for " + query, Toast.LENGTH_SHORT).show();
        //Then makes the HTTP request from the Google API
        AsyncHttpClient client = new AsyncHttpClient();
        imageResults.clear(); 
        int offset = 0;
        FilterPreferences = getFilterPreferences();
        client.get("https://ajax.googleapis.com/ajax/services/search/images?rsz=8&" + 
        FilterPreferences + "start=" + offset + "&v=1.0&q=" + Uri.encode(query),
                new JsonHttpResponseHandler() { //A handler is set in case the search doesn't work
                @Override
                public void onSuccess(JSONObject response) {
                    JSONArray imageJsonResults = null;
                    try {
                        imageJsonResults = response.getJSONObject("responseData")
                            .getJSONArray("results");
                        imageAdapter.addAll(ImageResult
                            .fromJSONArray(imageJsonResults));
                        Log.d("DEBUG", imageResults.toString());
                    } catch (JSONException e) {
                    e.printStackTrace();
                    }
                } //End onSuccess
        }); //End client.get()  

    } //End onImageSearch 

    //Spells out all my filter preferences by using the API "language" put into variables
    //and ultimately becomes a part of the getFilterPreferences method
    public String getFilterPreferences() {

        String filterPreferences, imageType, imageSize, colorFilter = null;

        SharedPreferences filters = getSharedPreferences(AdvancedOptionsActivity.FILTERS, 0);

        switch(filters.getInt("image_type", 0)) {
            case 0:  imageType = "";                 break;
            case 1:  imageType = "&imgtype=face";    break;
            case 2:  imageType = "&imgtype=photo";   break;
            case 3:  imageType = "&imgtype=lineart"; break;
            case 4:  imageType = "&imgtype=clipart"; break;
            default: imageType = "";
        }
        switch(filters.getInt("color_filter", 0)) {
            case 0: colorFilter = "";                 break;
            case 1: colorFilter = "&imgcolor=blue";   break;
            case 2: colorFilter = "&imgcolor=red";    break;
            case 3: colorFilter = "&imgcolor=green";  break;
            case 4: colorFilter = "&imgcolor=orange"; break;
            case 5: colorFilter = "&imgcolor=gray";   break;
            default: colorFilter = "";
        }
        switch(filters.getInt("image_size", 0)) {
            case 0:  imageSize = "";              break;
            case 1:  imageSize = "&imgsz=small";  break;
            case 2:  imageSize = "&imgsz=medium"; break;
            case 3:  imageSize = "&imgsz=large";  break;
            case 4:  imageSize = "&imgsz=xlarge"; break;
            default: imageSize = "";
        }

        filterPreferences = imageType + colorFilter + imageSize;
        //If selects nothing, it will still run the filterPreferences variable 
        //to include the default selections (filters shown in top row of spinner)
        if (filterPreferences.equals("")) return filterPreferences;
        else return filterPreferences + "&";

    }// End getFilterPreferences

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.search, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

我的第二个活动,包含所有微调器和过滤器选项:

package com.noni.gridimagesearch;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class AdvancedOptionsActivity extends Activity {

    private Spinner colorFilter, imageSize, imageType;
    protected static final String FILTERS = "FilterPreferences";
    private Button btnSubmit;
    private ArrayAdapter<CharSequence> imageSizeAdapter, colorFilterAdapter, imageTypeAdapter;

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

        setupViews();
        restoreFilterPreferences();
    }

    private void setupViews() {

        imageType = (Spinner) findViewById(R.id.image_type);
        imageTypeAdapter = ArrayAdapter.createFromResource(this, 
                R.array.image_type, android.R.layout.simple_spinner_item);
        imageTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        imageType.setAdapter(imageTypeAdapter);

        colorFilter = (Spinner) findViewById(R.id.color_filter);
        colorFilterAdapter = ArrayAdapter.createFromResource(this, 
                R.array.color_filter, android.R.layout.simple_spinner_item);
        colorFilterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        colorFilter.setAdapter(colorFilterAdapter);

        imageSize = (Spinner) findViewById(R.id.image_size);
        imageSizeAdapter = ArrayAdapter.createFromResource(this, 
                R.array.image_size, android.R.layout.simple_spinner_item);
        imageSizeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        imageSize.setAdapter(imageSizeAdapter);

        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                setResult(RESULT_OK, i);
                finish();
            }
        }); 
    }   

    private void restoreFilterPreferences() {
        SharedPreferences filters = getSharedPreferences(FILTERS, 0);

        int imageSizeSelection = filters.getInt("image_size", 0);
        imageSize.setSelection(imageSizeSelection);

        int colorFilterSelection = filters.getInt("color_filter", 0); 
        colorFilter.setSelection(colorFilterSelection);

        int imageTypeSelection = filters.getInt("image_type", 0);
        imageType.setSelection(imageTypeSelection);
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveFilterPreferences();
    }

    private void saveFilterPreferences() {
        SharedPreferences filters = getSharedPreferences(FILTERS, 0);
        SharedPreferences.Editor editor = filters.edit();
        editor.putInt("image_size", imageSize.getSelectedItemPosition()); 
        editor.putInt("color_filter", colorFilter.getSelectedItemPosition());
        editor.putInt("image_type", imageType.getSelectedItemPosition()); 
        editor.commit(); 
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.advanced_options, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:0)

我看到现在发生了什么,毕竟是一个简单的错误。第一个Activity中colorFilter变量的case语句有第一行读取空字符串case 0: imageType = ""; break;但是在我的微调器中,我没有在下拉列表的顶部创建一个字符串允许这个空字符串,所以我的所有颜色都在列表中向下移动了一个。所以列表中的第一种颜色,蓝色,实际上采用了列表中的最后一种颜色,灰色,因为它从最后一个位置突然出现。

无论如何,这么多代码如此困在这么简单的错误上,但很高兴我发现了它。这些错误确实是最难的,因为它们永远不会在LogCat中找到,也不是红色错误。