How can I keep my RecyclerView after android rotation?

When I rotate my device, my activity instance is destroyed which starts a new onCreate. I can’t figure out how to repopulate my RecyclerView after screen orientation. I have tried some solutions involing AndroidManifest: android:configChanges="keyboardHidden|orientation" and also with onSaveInstanceState, but could not get it to work. I have addedonSaveInstanceStateandonRestoreInstanceState` base code to my question, which does not do anything at the moment.


public class MainActivity extends AppCompatActivity implements RepositoryAdapter.OnItemClickListener {

    private static final String LOG_TAG = "MainActivity";

    FloatingActionButton fabSearchGitHubUser;

    EditText etSearchUser;

    Button btnSearchUser;

    TextView tvOwner;

    RecyclerView mRecyclerView;

    private RepositoryAdapter mAdapter;

    private Api mApi;

    private Owner mOwner;

    boolean isSearchToggled = false;

    protected void onCreate(Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) findViewById(;

        mApi = ApiUtils.getApi();

        // RecyclerView
        RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());

        // Floating action button to toggle user search field.
        FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(;
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

    public void onSaveInstanceState(Bundle savedInstanceState) {

    public void onRestoreInstanceState(Bundle savedInstanceState) {

    public void onSearchBtnClicked(View view) {
        if (!TextUtils.isEmpty(etSearchUser.getText())) {
            String searchedUser = etSearchUser.getText().toString();

            // Search will be done offline when no internet, otherwise online.
            if (!isNetworkAvailable()) {
                Toast.makeText(this, "No internet, searching offline", Toast.LENGTH_SHORT).show();
                mOwner = Owner.getByUsername(searchedUser);
                if (mOwner != null) {
                } else {
                    if (mAdapter != null) {
                    tvOwner.setText(getString(R.string.user_not_found, searchedUser));
            } else {
                Toast.makeText(this, "Searching online", Toast.LENGTH_SHORT).show();
        } else {
            Log.i(LOG_TAG, "Search field is empty");

        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);


     * Search local user by username.
     * @param username The local user that is searched for.
    public void searchByUsername(String username) {
        mAdapter = new RepositoryAdapter(Repository.getList(username), MainActivity.this);

     * Search online on GitHub to retrieve all user repositories.
     * @param username The GitHub user that is searched for.
    public void loadRepository(String username) {
        mApi.listRepository(username).enqueue(new Callback<List<Repository>>() {
            public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
                mAdapter = new RepositoryAdapter(response.body(), MainActivity.this);

            public void onFailure(Call<List<Repository>> call, Throwable t) {
                Log.e("MainActivity", "error loading from API");

    public void onItemClick(Repository repository) {
        if (isNetworkAvailable()) {
            mOwner = Owner.getByUsername(repository.owner.getLogin());
            Repository mRepository = Repository.getByRepositoryName(repository.getName());

            if (mOwner != null) {
                if (mRepository != null) {
                    // Repository is already in Database.
                } else {
                    // Selected repository is added to Database
                    mRepository = new Repository(mOwner);
            } else {
                // selected repository and its owner are added to Database
                mOwner = new Owner();

                mRepository = new Repository(mOwner);

        // Send intent with repository name to repository detail activity.
        Intent intent = new Intent(MainActivity.this, RepositoryDetailActivity.class);
        intent.putExtra(INTENT_KEY_REPOSITORY, repository.getName());

     * Toggle search field according to its state.
    private void toggleSearch() {
        if (!isSearchToggled) {
            isSearchToggled = true;
        } else {
            isSearchToggled = false;

     * Checks if network is available on the device.
     * @return Return when networkInfo is not null and networkInfo is connected.
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();

Find images based on an ID [on hold]

I have a request, I have to read some images based on a number written in the image, for example, runners use a number to run a marathon, pictures are taken and then i need to look in 1000s images based on that number, Do you guys know any library in any language that has that functionality

If there is anyone in PHP i’ll be thanksful!

Export and get all results with pagination

I have an endpoint that collects data and executes a method (getAdminInfo) that’ll break down the results using pagination. Where ‘0’ represents what page to begin on, and ‘4000’ represents # of records per page.

getAdminInfo(0, 4000, drawNum, searchString, sortOrder, colNo)

The problem I am having is the exported results contains rows only from the first page rather than all records.

public void downloadUserAction(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(DRAW_PARAM) int drawNum,
        @RequestParam(value=SEARCH_PARAM) String searchString,
        @RequestParam(value=SORT_PARAM) int colNo,
        @RequestParam(value=SORT_ORDER) String sortOrder,
        Model model) throws JSONException, IOException
    response.addCookie(new Cookie("fileDownload", "true")); 
    String jsonString = adminPageInfo.getAdminInfo(0, 4000, drawNum, searchString, sortOrder, colNo);           
    JSONArray names = new JSONArray(CSV_COLUMN_NAMES_IN_ORDER);
    JSONArray docs = convertToJsonArray(jsonString);
    String csv = CDL.toString(names, docs);
    StringBuilder builder =  new StringBuilder();
    streamCSVContent(response, builder.toString());

This is my code for the export to csv related functions

private String generateCSVColumnHeader() 
    StringBuilder builder =  new StringBuilder();
    for(String name : CSV_COLUMN_NAMES_IN_ORDER)
    return builder.toString();

private void streamCSVContent(HttpServletResponse response, String csv)
        throws IOException 
    InputStream s2 = new ByteArrayInputStream(csv.getBytes());
    IOUtils.copy(s2, response.getOutputStream());


private JSONArray convertToJsonArray(String jsonString)
        throws JSONException 
    JSONObject output;
    output = new JSONObject(jsonString);
    JSONArray docs = output.getJSONArray(USER_ACTIVITIES);
    return docs;

private void settingResponseTypeAndHeader(HttpServletResponse response)
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; "
            + "filename="%s"",
    response.setHeader(headerKey, headerValue);

This is my code for collecting data + pagination

public String getAdminInfo(int pageNo, int length, int drawNum, String searchString, String sortOrder,
        int sortColNum) throws JsonProcessingException {
    UserActionResponse userActionResponse = new UserActionResponse();
    List<UserAction> result = new ArrayList<>();
    Sort.Direction sortDirection = Sort.Direction.ASC;
    if (sortOrder.equalsIgnoreCase("ASC")) {
        sortDirection = Sort.Direction.ASC;
    if (sortOrder.equalsIgnoreCase("DESC")) {
        sortDirection = Sort.Direction.DESC;
    String columnName = supportedColumnMap.get(sortColNum);
    if (columnName == null) {
        columnName = supportedColumnMap.get(6);
    result = findUserActionRecords(length, pageNo, columnName, sortDirection, searchString);

    int totalRecord = 0;
    if (searchString != null && searchString.length() != 0) {
        totalRecord = (int) userActionRepository.count(searchString);
    } else {
        totalRecord = (int) userActionRepository.count();

    addRowNums(result, length, pageNo);
    objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
    return objectMapper.writerWithView(Views.AdminPageView.class).writeValueAsString(userActionResponse);


private List<UserAction> findUserActionRecords(int pageSize, int currentPage, String sortField,
        Sort.Direction sortDirection, String searchString) {
    Pageable pageable = new PageRequest(currentPage, pageSize, sortDirection, sortField);
    Page<UserAction> page;
    if (searchString == null || searchString.length() == 0) {
        page = userActionRepository.findAll(pageable);
    } else {
        page = userActionRepository.findAll(searchString, pageable);
    return page.getContent();

Is there any way I can modify this to when I access /downloadUserAction I can apply pagination and still retrieve all records in each page in one file when exporting csv?

Converting RSS Feed XML to JSON using Java is Displaying Special Characters

Created a Spring MVC based Restful Controller which takes a hardcoded RSS HTTP URL and converts it from XML to JSON:



import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.json.XML;

import com.fasterxml.jackson.databind.ObjectMapper;

public class RssFeedController {

    private HttpHeaders headers = null;

    public RssFeedController() {
        headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");

    @RequestMapping(value = "/v2/convertToJson", method = RequestMethod.GET, produces = "application/json")
    public String getRssFeedAsJson() throws IOException {
        InputStream xml = getInputStreamForURLData("");
        String xmlString = IOUtils.toString(xml);
        JSONObject jsonObject = XML.toJSONObject(xmlString);
        ObjectMapper objectMapper = new ObjectMapper();
        Object json = objectMapper.readValue(jsonObject.toString(), Object.class);
        String response = objectMapper.writeValueAsString(json);
        return response;

    public static InputStream getInputStreamForURLData(String targetUrl) {
        URL url = null;
        HttpURLConnection httpConnection = null;
        InputStream content = null;

        try {
            url = new URL(targetUrl);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            httpConnection = (HttpURLConnection) conn;
            int responseCode = httpConnection.getResponseCode();
            content = (InputStream) httpConnection.getInputStream();
        catch (MalformedURLException e) {
        catch (IOException e) {
        return content;




So, the original RSS Feed has the following content:

    <title>October Fest Weekend</title>
    <pubDate>Wed, 04 Oct 2017 17:08:48 +0000</pubDate>
    <dc:creator><![CDATA[John Doe]]></dc:creator>

    <guid isPermaLink="false"></guid>
<p>Doors Open:6:30pm<br />
Show Begins:  7:30pm<br />
Show Ends (Estimated time): 11:00pm<br />
Location: Staples Center</p>
<p>Map of ...</p>
<p>The post <a rel="nofollow" href="">OctoberFest Weekend</a> appeared first on <a rel="nofollow" href="">SampleFeed</a>.</p>

This renders into JSON like this:

    "guid": {
        "content": "",
        "isPermaLink": false
    "pubDate": "Wed, 04 Oct 2017 17:08:48 +0000",
    "category": "Uncategorized",
    "title": "October Fest Weekend",
    "description": "<p>n??</p>n<p>Doors Open:6:30pm<br />nShow Begins:?? 7:30pm<br />nShow Ends (Estimated time):??11:00pm<br />nLocation: Staples Center</p>n<p>Directions</p>n<p>Map of ...</p>n<p>The post <a rel="nofollow" href="">OctoberFest Weekend</a> appeared first on <a rel="nofollow" href="">Sample Feed</a>.</p>n",
    "dc:creator": "John Doe",
    "link": "",
    "comments": ""

Please notice in the rendered JSON that there are two question marks (“??”) right after inside the value for the “description” key like this:

"description": "<p>n??</p>n

Also, there are two more question marks right here after the Show Begins:

<br />nShow Begins:??

And also before 11:00 p.m.

Show Ends (Estimated time):??11:00pm<br />

This isn’t the only pattern that is displaying special characters, there also places where there are three ??? marks generated and also some places like ?????


<title>Today’s 20th Annual Karaoke</title>

renders like this in JSON:

"title": "Today???s 20th Annual Karaoke"


<content-encoded>: <![CDATA[(Monte Vista High School, NY.).  </span></p>]]></content:encoded>

Renders like this in JSON:

"content:encoded":  "(Monte Vista High School, NY.).????</span></p>

There’s places where the XML has a like a dash (“-“):

<strong>Welcome</strong> – Welcome to the Party!

Which gets rendered in JSON:

<strong>Welcome</strong>????? Welcome to the Party!

Does anyone know how to set the proper encoding in my code so I can avoid these bad / special characters rendering issues?

@Binds methods must have only one parameter whose type is assignable to the return type

I am migrating to the new dagger android 2.11

All set up based on the Google blueprint :MVP-Dagger.but I am having this error :

Error:(22, 57) error: @Binds methods must have only one parameter
whose type is assignable to the return type

Here in this line :

    @Binds abstract PresenterFactory<MainContract.Presenter> providePresenterFactory(MainPresenter presenter);

The presenter :

public class MainPresenter extends BasePresenterImpl<MainContract.View>
    implements MainContract.Presenter { public MainPresenter(String s) {..
} ... }

Someone have any idea on how to solve this? Thanks.

how to convert seconds to minutes using android studio by the support of simple_list_item_checked?

**I want to convert from second to minutes or hours and days… etc I tried to use the simple_list_item_checked to check the two time measures that the user want to use and here is the code please help me with it am beginner with android **`

public class Time extends AppCompatActivity {
EditText editText2;
Button button;
TextView textView5;

protected void onCreate(Bundle savedInstanceState) {
    ListView tList1=(ListView)findViewById(;
    ListView tList2=(ListView)findViewById(;

    ArrayList<String> t1=new ArrayList<>();
    ArrayAdapter<String> adapter1=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked,t1);
    ArrayList<String>t2=new ArrayList<>();
    ArrayAdapter<String>adapter2=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked,t2);

    tList1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position){
                case 0:
                    Double second=1.0;
                    Double minute=second*60;
                    Double hour=minute*60;
                    Double day=hour*24;
                    Double month=day*30;
                    Double year=month*12;
                    Double decade=year*10;
                    Double century=decade*10;
                    second = Double.parseDouble(editText2.getText().toString());

                    String string=editText2.getText().toString();
                    if (second !=0){

What do the following parameters return an error?

I am extending a class called Point :

public class Point{
  public double pt1;
  public double pt2;

  Point (double pt1, double pt2){
    this.pt1 = pt1;
    this.pt2 = pt2;
  public double distanceTo(Point that){
    double x = this.pt1 - that.pt1;
    double y = this.pt2 - that.pt2;
    return Math.sqrt(x * x + y * y);
  public static void main(String[] args){
    Point a = new Point(3, 0); 
    Point b = new Point(0, 4); 
    //System.out.println((new Point(1, 1)).distanceTo(new Point())); //Check what's wrong here!

With this program called Line:

public class Line extends Point{
  Point a;
  Point b;

  //Line constructor
  Line (Point a, Point b){
    this.a = a;
    this.b = b;
  public double length(){
    Point x = this.a;
    Point y = this.b;
    double pt1 = x.pt1;
    double pt2 = y.pt2;
    return pt1.distanceTo(pt2);

  public static void main(String[] args){
    Line a = new Line(new Point(0, 0), new Point (1, 1)); 

However, I keep getting the following error:

2 errors found:
File: /...  [line: 6]
Error: constructor Point in class Point cannot be applied to given types;
  required: double,double
  found: no arguments
  reason: actual and formal argument lists differ in length
File: /... [line: 15]
Error: double cannot be dereferenced

Why can I not give the Line constructor two Point(s) as parameters? Any advise will be helpful.

Checkout Class Using ArrayList

I have created a class called Checkout and within it i have to implement multiple methods. Im really confused on how to use an arrayList in these methods.

package assignment2;

import java.util.*;

public class Checkout extends java.lang.Object {

ArrayList<String> items;
int numberOfItems;

public Checkout(){
    this.items = new ArrayList<String>();

public int numberOfItems(){
    //Returns the number of DessertItem's in the list

public void enterItem(DessertItem item){
    //A DessertItem is added to the end of the list of items

public void clear(){
    //Clears the Checkout to begin checking out a new set of items

public int totalCost(){
    //Returns total cost of items in cents (without tax)

public int totalTax(){
    //Returns total tax on items in cents