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.

Thanks

MainActivity.java

public class MainActivity extends AppCompatActivity implements RepositoryAdapter.OnItemClickListener {

    private static final String LOG_TAG = "MainActivity";

    @BindView(R.id.fab_search_github_user)
    FloatingActionButton fabSearchGitHubUser;

    @BindView(R.id.et_search_user)
    EditText etSearchUser;

    @BindView(R.id.btn_search_user)
    Button btnSearchUser;

    @BindView(R.id.github_user)
    TextView tvOwner;

    @BindView(R.id.github_repository_recyclerview)
    RecyclerView mRecyclerView;

    private RepositoryAdapter mAdapter;

    private Api mApi;

    private Owner mOwner;

    boolean isSearchToggled = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ButterKnife.bind(this);

        mApi = ApiUtils.getApi();

        // RecyclerView
        RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setHasFixedSize(true);

        // Floating action button to toggle user search field.
        FloatingActionButton floatingActionButton = (FloatingActionButton) findViewById(R.id.fab_search_github_user);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggleSearch();
            }
        });
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @OnClick(R.id.btn_search_user)
    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) {
                    searchByUsername(searchedUser);
                    tvOwner.setText(searchedUser);
                } else {
                    if (mAdapter != null) {
                        mAdapter.clearRecyclerView();
                    }
                    tvOwner.setText(getString(R.string.user_not_found, searchedUser));
                }
            } else {
                loadRepository(searchedUser);
                tvOwner.setText(searchedUser);
                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);
        }

        toggleSearch();
    }

    /**
     * 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);
        mRecyclerView.setAdapter(mAdapter);
    }

    /**
     * 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>>() {
            @Override
            public void onResponse(Call<List<Repository>> call, Response<List<Repository>> response) {
                mAdapter = new RepositoryAdapter(response.body(), MainActivity.this);
                mRecyclerView.setAdapter(mAdapter);
            }

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

    @Override
    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);
                    mRepository.setName(repository.getName());
                    mRepository.setLogin(repository.owner.getLogin());
                    mRepository.setDescription(repository.getDescription());
                    mRepository.setStargazersCount(repository.getStargazersCount());
                    mRepository.setForksCount(repository.getForksCount());
                    mRepository.save();
                }
            } else {
                // selected repository and its owner are added to Database
                mOwner = new Owner();
                mOwner.setLogin(repository.owner.getLogin());
                mOwner.setAvatarUrl(repository.owner.getAvatarUrl());
                mOwner.setReposUrl(repository.owner.getReposUrl());
                mOwner.save();

                mRepository = new Repository(mOwner);
                mRepository.setName(repository.getName());
                mRepository.setLogin(repository.owner.getLogin());
                mRepository.setDescription(repository.getDescription());
                mRepository.setStargazersCount(repository.getStargazersCount());
                mRepository.setForksCount(repository.getForksCount());
                mRepository.save();
            }
        }

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

    /**
     * Toggle search field according to its state.
     */
    private void toggleSearch() {
        if (!isSearchToggled) {
            etSearchUser.setVisibility(View.VISIBLE);
            btnSearchUser.setVisibility(View.VISIBLE);
            isSearchToggled = true;
        } else {
            etSearchUser.setVisibility(View.GONE);
            btnSearchUser.setVisibility(View.GONE);
            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.

@RequestMapping("/downloadUserAction")
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
{   
    settingResponseTypeAndHeader(response);
    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);
    preparingJsonAsPerCSV(docs);
    String csv = CDL.toString(names, docs);
    StringBuilder builder =  new StringBuilder();
    builder.append(generateCSVColumnHeader()).append("n").append(csv);
    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)
    {
        builder.append(name).append(",");
    }
    return builder.toString();
}

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

    return;
}

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)
{
    response.setContentType("text/csv");
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; "
            + "filename="%s"",
            DOWNLOAD_FILE_NAME);
    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);
    userActionResponse.setDraw(drawNum);
    userActionResponse.setUserActivities(result);
    userActionResponse.setRecordsTotal(totalRecord);
    userActionResponse.setRecordsFiltered(totalRecord);
    objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
    return objectMapper.writerWithView(Views.AdminPageView.class).writeValueAsString(userActionResponse);
}

pagination:

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:

RssFeedController:

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.json.XML;

import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
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("http://www.samplefeed.com/feed");
        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) {
            e.printStackTrace();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

pom.xml

<dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20170516</version>
    </dependency>

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>

So, the original RSS Feed has the following content:

<item>
    <title>October Fest Weekend</title>
    <link>http://www.samplefeed.com/feed/OctoberFestWeekend</link>
    <comments>http://www.samplefeed.com/feed/OctoberFestWeekend/#comments</comments>
    <pubDate>Wed, 04 Oct 2017 17:08:48 +0000</pubDate>
    <dc:creator><![CDATA[John Doe]]></dc:creator>
            <category><![CDATA[Uncategorized]]></category>

    <guid isPermaLink="false">http://www.samplefeed.com/feed/?p=9227</guid>
    <description><![CDATA[<p>
</p>
<p>Doors Open:6:30pm<br />
Show Begins:  7:30pm<br />
Show Ends (Estimated time): 11:00pm<br />
Location: Staples Center</p>
<p>Directions</p>
<p>Map of ...</p>
<p>The post <a rel="nofollow" href="http://www.samplefeed.com/feed/OctoberFestWeekend/">OctoberFest Weekend</a> appeared first on <a rel="nofollow" href="http://www.samplefeed.com">SampleFeed</a>.</p>
]]></description>

This renders into JSON like this:

{
    "guid": {
        "content": "http://www.samplefeed.com/feed/?p=9227",
        "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="http://www.samplefeed.com/feed/OctoberFestWeekend/">OctoberFest Weekend</a> appeared first on <a rel="nofollow" href="http://www.samplefeed.com">Sample Feed</a>.</p>n",
    "dc:creator": "John Doe",
    "link": "http://www.samplefeed.com/feed/OctoberFestWeekend",
    "comments": "http://www.samplefeed.com/feed/OctoberFestWeekend/#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 ?????

e.g.

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

renders like this in JSON:

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

And

<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 :

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

The presenter :

@ActivityScoped
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;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_time);
    ListView tList1=(ListView)findViewById(R.id.tList1);
    ListView tList2=(ListView)findViewById(R.id.tList2);
   editText2=(EditText)findViewById(R.id.editText2);
    button=(Button)findViewById(R.id.button);
    textView5=(TextView)findViewById(R.id.textView5);



    ArrayList<String> t1=new ArrayList<>();
    t1.add("Seconds");t1.add("Minutes");t1.add("Hours");t1.add("Days");t1.add("Months");t1.add("Year");
    t1.add("Decade");t1.add("Century");
    ArrayAdapter<String> adapter1=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked,t1);
    tList1.setAdapter(adapter1);
    ArrayList<String>t2=new ArrayList<>();
    t2.add("Seconds");t2.add("Minutes");t2.add("Hours");t2.add("Days");t2.add("Months");t2.add("Year");
    t2.add("Decade");t2.add("Century");
    ArrayAdapter<String>adapter2=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked,t2);
    tList2.setAdapter(adapter2);

    tList1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        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());
                   second.parseDouble(editText2.getText().toString());
                    Toast.makeText(getApplicationContext(),minute.toString(),Toast.LENGTH_LONG).show();

                    String string=editText2.getText().toString();
                    textView5.setText(string);
                    editText2.setText("");
                    if (second !=0){
                        textView5.setText(minute.toString());
                    }

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(a.distanceTo(b)); 
    //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)); 
    System.out.println(a.length()); 
  }
}

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
}

}