简体   繁体   English

如何在Mainactivity和Android中的另一个类之间传递全局计数器?

[英]How to pass global counter between Mainactivity & another class in android?

When i click on forward button it should increment page_counter, if there are no books to display it will put toast message, all this happens in onClick. 当我单击前进按钮时,它应该增加page_counter,如果没有要显示的书籍,它将发布祝酒消息,所有这些都发生在onClick中。 When i click to go back, it decrements page counter, this happens in onClick too. 当我单击返回时,它会减少页面计数器,这也发生在onClick中。

ddd

The problem is that i connect with ProcessData class(which loads book covers) only through execute() method which takes only one argument - search word("java" in this case) 问题是我只能通过仅带有一个参数的execute()方法与ProcessData类(加载书的封面)连接-搜索单词(在这种情况下为“ java”)

How do i get this global-page_counter accessed from inside processdata class so i can load next/previous book covers? 我如何从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

 }
}

So basically, how do I pass another argument between classes if they connect only through 1 method taking 1 argument? 因此,基本上,如果它们仅通过采用1个参数的1个方法进行连接,该如何在类之间传递另一个参数?

EDIT: for the user Dima, my code here 编辑:对于用户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;
  }

}

0) You should create ProcessData object every time you want to call execute. 0)每次要调用execute时,都应创建ProcessData对象。

1) You can make ProcessData inner class of MainActivity. 1)您可以使ProcessData成为MainActivity的内部类。

2) You can pass this counter to constructor of ProcessDataTask 2)您可以将此计数器传递给ProcessDataTask的构造函数

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

private static global_page_counter = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM