如何在Mainactivity&amp ;;之间传递全局计数器android中的另一个类?

时间:2015-03-31 14:56:16

标签: java android design-patterns parameter-passing

当我点击前进按钮时,它应该增加page_counter,如果没有要显示的书籍,它会输出toast消息,所有这些都发生在onClick上。 当我点击返回时,它会减少页面计数器,这也会发生在onClick上。

ddd

问题是我只通过execute()方法连接ProcessData类(它加载书籍封面),该方法只接受一个参数 - 搜索词(" java"在这种情况下)

如何从processdata类中访问此global-page_counter,以便我可以加载下一个/上一个书籍封面?

public class MainActivity extends Activity {

int global_page_counter = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    final ProcessData data = new ProcessData();
    // only search query goes into processdata!
    //how to pass/access more?
    data.execute("java");


    final ImageButton forward_button = (ImageButton)findViewById(R.id.forward_button);

    forward_button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0){

            if(data.isDataAvailable(search_query, global_page_counter) == false)
                Toast.makeText(getApplicationContext(),
                        "no more books", Toast.LENGTH_LONG).show();
            else {
                global_page_counter++ ;
                data.execute(search_query);
            }
        }
    });
    }


public class ProcessData extends AsyncTask<String, Void, String> {
private final String LOG_TAG = ProcessData.class.getSimpleName();

private List<Book> booksList ;

Uri destinationURL ;
public ProcessData(){
    booksList = new ArrayList<Book>();
    destinationURL = null ;
}


//checks if there is more images to load
public boolean isDataAvailable(String query, int page_counter){
     String validUrl = createValidURL(query, page_counter);
     if(validUrl.length() < 30) return false ;
  return true ;
}

 private String createValidUrl(String search_query){
     ......//some code here
}

//this method receives "java" search from execute() in mainActivity
public String doInBackground(String ...params) {

    String validUrl = createValidURL(params[0]  );//params[0] is java

 }
}

基本上,如果只通过1个方法连接一个参数来连接类,如何在类之间传递另一个参数?

编辑:对于用户Dima,我的代码在这里

public class ProcessData extends AsyncTask<String, Void, String> {
private final String LOG_TAG = ProcessData.class.getSimpleName();

private List<Book> booksList ;
private static boolean isDataAvailable ;
private int page_count ;

Uri destinationURL ;
public ProcessData(){
    booksList = new ArrayList<Book>();
    destinationURL = null ;
}

public ProcessData(int page_counter, boolean isDataAvailable){
    booksList = new ArrayList<Book>();
    destinationURL = null ;
    page_count = page_counter;
    this.isDataAvailable = true ;
}

public static boolean getIsDataAvailable(){
    return isDataAvailable ;
}
public int get_page_counter(){
    return page_count ;
}

/*public boolean isDataAvailable(String query, int page_counter){
     String validUrl = createValidURL(query, page_counter);
     String bufferData = MakeConnectionAndStoreBufferData(validUrl);

     if(bufferData.length() < 30) return false ;
  return true ;
}*/

 private String createValidURL(String query, int page_counter) {
    String BASE_URL = "http://it-ebooks-api.info/v1/search";

    String resultUrl = null ;
    if (page_counter == 0){
        Log.d(LOG_TAG, "page is zero!");
        destinationURL = Uri.parse(BASE_URL).buildUpon()
                .appendPath(query)
                .appendQueryParameter("type", "title")
                .build();

    resultUrl = destinationURL.toString();
    resultUrl = resultUrl.replace("?", "&" );
  }
   else if(page_counter > 0){
        Log.d(LOG_TAG,"page is bigger than zero! page counter is: " +  page_counter);
        destinationURL = Uri.parse(BASE_URL).buildUpon()
                .appendPath(query)
                .appendQueryParameter( "type", "title")
                .appendQueryParameter("page",  Integer.toString(page_counter) )
                .build();

        resultUrl = destinationURL.toString();
        resultUrl = resultUrl.replace("?", "&");

    }

    return resultUrl ;
}

 private String MakeConnectionAndStoreBufferData(String validUrl){

  Log.d(LOG_TAG, "VALID url:" + validUrl);

HttpURLConnection urlConnection = null;
BufferedReader reader = null;

  try {
    URL url = new URL(validUrl);

    urlConnection = (HttpURLConnection) url.openConnection();
    if(urlConnection == null)
        Log.e(LOG_TAG, "url connection is null! ERROR");

    urlConnection.setRequestMethod("GET");

    try {
        urlConnection.connect();
    }catch(Exception e){
        Log.e(LOG_TAG, "exception : " + e );
    }

    InputStream inputStream = urlConnection.getInputStream();
    if(inputStream == null) {
        Log.e(LOG_TAG, "input stream failed to create!!!");
        return null;
    }
    StringBuffer buffer = new StringBuffer();

    reader = new BufferedReader(new InputStreamReader(inputStream));

    String line;
    while((line = reader.readLine()) != null) {
        buffer.append(line + "\n");
    }
        Log.d(LOG_TAG, " ");
    return buffer.toString();

} catch(IOException e) {
    Log.e(LOG_TAG, "Error", e);
    return null;
} finally {
    if(urlConnection != null) {
        urlConnection.disconnect();
    }
    if(reader != null) {
        try {
            reader.close();
        } catch(final IOException e) {
            Log.e(LOG_TAG,"Error closing stream", e);
        }
    }
  }
 }

public List<Book> getBooksList() {
    return booksList;
}

private void convertBufferDataIntoBook(String data) {

    final String BOOK_ID = "ID";
    final String BOOK_TITLE = "Title";
    final String BOOK_SUBTITLE = "SubTitle";
    final String BOOK_DESCRIPTION = "Description";
    final String BOOK_IMAGE = "Image";
    final String BOOK_ISBN = "isbn";

    //parsing raw buffer into clean nice Book object using json parser
    try {

        JSONObject jsonData = new JSONObject(data);
        JSONArray books_items = jsonData.getJSONArray("Books");

        for(int i=0; i<books_items.length(); i++) {

            JSONObject jsonBook = books_items.getJSONObject(i);

            long id = jsonBook.getLong(BOOK_ID);
            String book_title = jsonBook.getString(BOOK_TITLE);
            String book_subtitle = "";
            try {
                book_subtitle = jsonBook.getString(BOOK_SUBTITLE);
            }catch(JSONException e){
                   //sometime subtitle is missing!
                Log.d(LOG_TAG, "SUBTITLE IS MISSING NOW!");
                   book_subtitle = "N/A";
            }

            String book_description = jsonBook.getString(BOOK_DESCRIPTION);
            String book_image = jsonBook.getString(BOOK_IMAGE);
            String book_isbn = jsonBook.getString(BOOK_ISBN);

            Book book = new Book(id, book_title, book_subtitle, book_description, book_image, book_isbn);
            this.booksList.add(book);
        }
    } catch(JSONException jsone) {
        jsone.printStackTrace();
        Log.e(LOG_TAG,"Error processing Json data");
    }

}

public String doInBackground(String ...params) {


    String validUrl = createValidURL(params[0], get_page_counter()  );

    String result_buffer = MakeConnectionAndStoreBufferData(validUrl);
    if(result_buffer.length() < 30){
        isDataAvailable = false ;
        return "" ;
    }

    convertBufferDataIntoBook(result_buffer);

    return result_buffer;
  }

}

2 个答案:

答案 0 :(得分:2)

0)每次要调用execute时都应该创建ProcessData对象。

1)您可以创建MainActivity的ProcessData内部类。

2)您可以将此计数器传递给ProcessDataTask的构造函数

答案 1 :(得分:1)

您的数据加载类是内部类,因此只需将计数创建为静态变量

private static global_page_counter = 0