Categories
discuss

How to add delimiter while writing .csv file using openCSV

I’m writing a csv file in java and i want to write csv file with ‘|’ as delimiter. How can i do in my code.

This is my Java code:

public void createCsv(User user) {
    
    try( FileWriter writer = new FileWriter(CSV_FILE_NAME,true);
            CSVWriter csvWriter = new CSVWriter(writer,
                    CSVWriter.DEFAULT_SEPARATOR,
                    CSVWriter.NO_QUOTE_CHARACTER,
                    CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                    CSVWriter.DEFAULT_LINE_END);
            
            CSVReader reader = new CSVReader(new FileReader(CSV_FILE_NAME));){
        
        if(reader.readNext() !=null) {
            csvWriter.writeNext(new String[]{user.getFirstName(), user.getLastName()});             
        }else {
            String[] headerRecord = {"First Name", "Last Name"};
            csvWriter.writeNext(headerRecord);

            csvWriter.writeNext(new String[]{user.getFirstName(), user.getLastName()});             
        }
        
        
        
    } catch (IOException e) {
        
        e.printStackTrace();
    }
}

Answer

Use this snippet for instantiating CSVWriter.

CSVWriter csvWriter = new CSVWriter(writer,
                                    '|',
                                    CSVWriter.NO_QUOTE_CHARACTER,
                                    CSVWriter.DEFAULT_ESCAPE_CHARACTER,
                                    CSVWriter.DEFAULT_LINE_END);
Categories
discuss

Save arguments for later Javascript

The title of this question is probably misleading. I’m having some trouble wrapping my head around this concept. I want to pass all of the arguments into a function, but call it with those arguments later.

I’m currently doing something like this:

function copyRecords(userId, options) {
    const getRecordsWrapper = (userId, options) => () => getRecords(userId, options);
    abstractionService = new MyAbstractionService(getRecordsWrapper);
    ...etc
}

This is where I would save and later call the function:

class MyAbstractionService {
    constructor(getRecords) {
        this.getRecords = getRecords;
    }
    performSomeAction() {
        return this.getRecords();
    }
}

I need to do this because getRecords takes different arguments in different areas, and I want to abstract them into one service without having to pass a bunch of arguments into the service. That will get messy, as I need to do this for some other functions as well.

Am I thinking about this correctly? Is there another way to do this besides having a function return another function which returns my function? Also, not sure if this is important but getRecords returns a Promise. I don’t want to start working on the Promise until I’m in the abstraction service later though.

Answer

In functional programming terms, what you’re describing is Currying, and in JavaScript you can achieve the simplest idea of it using the bind() function:

const getRecordsWrapper = getRecords.bind(null, userId, options);

The first argument passed to bind is the function context (the this) of the to-be-called-later function, while the rest of the arguments are passed as regular arguments.

If you’re looking for a fully-featured functional programming framework in JavaScript, take a look at Ramda.js (for example).

Categories
discuss

HashMap.tableSizeFor(…). How does this code round up to the next power of 2?

Please, describe what these n| = n >>> x 5 lines do?

I am not interested in what | or >>> operators do. I am interested in what that complex logic do under cover in a math language.

/**
 * Returns a power of two size for the given target capacity.
 */
static final int tableSizeFor(int cap) {
    int n = cap - 1;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

Answer

All (positive) powers of two have exactly 1 bit set; and (power of 2 – 1) has all of the bits set less than the most significant bit. So, we can find the next largest power of two by

  • Subtracting 1
  • Setting all of the less significant bits
  • Adding 1 back

These bit shifting operations are implementing the second step of this process, by “smearing” the set bits.

So:

n |= n >>> 1;

Would do something like:

  01010000
| 00101000
= 01111000

If you do this again, you “smear” the number down again (still shifting by just 1):

  01111000
| 00111100
= 01111100

Keep on doing this, and you will end up with a number with all of the less significant bits set:

01111111

In the worst case, you’d have to do this 30 times (for a positive, signed 32 bit integer), when the most significant bit is the 31st bit:

   01xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
=> 011xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
=> 0111xxxxxxxxxxxxxxxxxxxxxxxxxxxx
=> 01111xxxxxxxxxxxxxxxxxxxxxxxxxxx
=> 011111xxxxxxxxxxxxxxxxxxxxxxxxxx
...
=> 01111111111111111111111111111111

(x just means it could be a zero or a one)

But you might notice something interesting: after the first smear, when shifting by 1, we have the two most significant bits set. So, instead of shifting by 1, we can skip an operation by shifting by 2:

   01xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
=> 011xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
=> 01111xxxxxxxxxxxxxxxxxxxxxxxxxxx

Continuing with this pattern, shift by 4 next:

=> 011111111xxxxxxxxxxxxxxxxxxxxxxx

Shift by 8:

=> 01111111111111111xxxxxxxxxxxxxxx

Shift by 16:

=> 01111111111111111111111111111111

So, instead of taking 30 operations to set all the less significant bits, we have taken 5.

Categories
discuss

Dagger2 issue with “cannot be provided without an @Provides-annotated method.”

I’m trying to setup a new project with Dagger2, I’ve used Dagger2 before, but now I’m trying to set it up from scratch by myself. I’m getting the example from a Kotlin project that I’m part of, but can’t set it up for Java the same way as it works in Kotlin right now (or maybe I’m missing something).

It’s just a single Component, single Module and Application.

Component

@Singleton
@Component(modules = {MainAppModule.class})
public interface AppComponent extends AndroidInjector<App> {
@Component.Builder
abstract class Builder implements AndroidInjector.Factory<App> {

    public AppComponent create(App application) {
        seedApplication(application);
        return build();
    }

    @BindsInstance
    abstract void seedApplication(App application);

    abstract AppComponent build();
}
}

Module

@Module
abstract class MainAppModule {

@Binds
abstract public Application bindApplication(App application);

@ContributesAndroidInjector
abstract public MainActivity contributeActivityInjector();
}

*Application *

public class App extends DaggerApplication {

@Override
public AndroidInjector<? extends DaggerApplication> applicationInjector() {
    return DaggerAppComponent.builder().create(this);
}
}

At this point I don’t have any classes that I call with @Inject I’m just getting error at build time:

 error: [dagger.android.AndroidInjector.inject(T)] java.util.Map<java.lang.Class<? extends android.content.BroadcastReceiver>,javax.inject.Provider<dagger.android.AndroidInjector.Factory<? extends android.content.BroadcastReceiver>>> cannot be provided without an @Provides-annotated method.
public interface AppComponent extends AndroidInjector<App> {
        ^ 

Of course cannot be provided without an @Provides-annotated method. seems to be the problem, but I just don’t know how to solve it. It works fine on my kotlin project, that somebody else set up.

Answer

It looks like you are missing AndroidInjectionModule (or AndroidSupportInjectionModule if you use support fragments) installed on you AppComponent.

It should be like:

@Component(modules = {AndroidInjectionModule.class, MainAppModule.class})
Categories
discuss

RecyclerView + MediaPlayer + Toggle Button + String Uri

Background: I’m working on an Fitness app. Everything is working good till now but problem came when I was working with audio files MediaPlayer in android.

I have checked resources and found ListView but couldn’t find anything on RecyclerView + MediaPlayer.

I want to know how to make it work while working with RecyclerView + Toggle Button + String Uri (Offline – Raw folder)

Problem: Right now it is playing the first .mp3 file on every click event (for Eng: R.raw.sample_one_eng is played and for Hindi: R.raw.sample_one_hindi is played). I think it is not taking int position into consideration.

Later, I would like to put it online (may be google cloud) since audio files (.mp3) are making my app quite heavy. Any ideas on that would be appreciated too (fast buffering, etc.).

ListExercises.java

public class ListExercises extends AppCompatActivity {

    List<ExerciseAudio> exerciseList = new ArrayList<>();
    RecyclerView.LayoutManager layoutManager;
    RecyclerView recyclerView;
    RecyclerViewAdapterAud adapter;
    PlayClickHandler clickHandler;

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

        initData();

        recyclerView = (RecyclerView) findViewById(R.id.list_ex);
        adapter = new RecyclerViewAdapterAud(exerciseList, getBaseContext());
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

    private void initData() {

        exerciseList.add(new ExerciseAudio(R.drawable.sample_one, "Sample Exercise One", "Sans One",
                R.raw.sample_one_eng,
                R.raw.sample_one_hindi));

        exerciseList.add(new ExerciseAudio(R.drawable.sample_two, "Sample Exercise Two", "Sans Two",
                R.raw.sample_two_eng,
                R.raw.sample_two_hindi));

        exerciseList.add(new ExerciseAudio(R.drawable.sample_three, "Sample Exercise Three", "Sans Three",
                R.raw.sample_three_eng,
                R.raw.sample_three_hindi));

        exerciseList.add(new ExerciseAudio(R.drawable.sample_four, "Sample Exercise Four", "Sans Four",
                R.raw.sample_four_eng,
                R.raw.sample_four_hindi));
    }
}

ViewExercise.java

public class ViewExercise extends AppCompatActivity {

    int image_id, eng_aud_url, hindi_aud_url;
    String name, sans_name;

    ArrayList<String> arrayList = new ArrayList<>();

    TextView timer, title, sansName;
    ImageView detail_image;
    ToggleButton tg_btn_speaker_eng, tg_btn_speaker_hindi;

    MediaPlayer mp;

    int position;

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

        Field[] field = R.raw.class.getFields();
        for (int i = 0; i < field.length; i++){
            arrayList.add(field[i].getName());
        }

        title = (TextView) findViewById(R.id.title);
        sansName = (TextView) findViewById(R.id.sans_name);
        detail_image = (ImageView) findViewById(R.id.detail_image);

        tg_btn_speaker_eng = (ToggleButton) findViewById(R.id.tg_btn_speaker_eng);
        tg_btn_speaker_hindi = (ToggleButton) findViewById(R.id.tg_btn_speaker_hindi);

        tg_btn_speaker_eng.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //toggleEnglish(tg_btn_speaker_eng.isChecked());
                int positionEng = 0;
                playSongEng(positionEng);
            }
        });

        tg_btn_speaker_hindi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //toggleHindi(tg_btn_speaker_hindi.isChecked());
                int positionHindi = 0;
                playSongHindi(positionHindi);
            }
        });

        if (getIntent() != null) {
            image_id = getIntent().getIntExtra("image_id", -1);
            name = getIntent().getStringExtra("name");
            sans_name = getIntent().getStringExtra("sanskrit_name");

            detail_image.setImageResource(image_id);
            title.setText(name);
            sansName.setText(sans_name);
        }
    }


    public void playSongEng(int i) {
        //mp.reset();
        int resId = getResources().getIdentifier(arrayList.get(i), "raw", getPackageName());
        mp = MediaPlayer.create(getApplicationContext(), resId);
        mp.start();
    }

    public void playSongHindi(int i) {
        //mp.reset();
        int resId = getResources().getIdentifier(arrayList.get(i), "raw", getPackageName());
        mp = MediaPlayer.create(getApplicationContext(), resId);
        mp.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mp != null)
            mp.release();
    }
}

This is how it looks!

Edit (to avoid confusion): Just noticed, that image name would have been List Exercises instead of View Exercise which corresponds to ListExercises.java

List Exercise - RecyclerView

And this one corresponds to ViewExercise.java

View Exercise

Thanks!

Answer

You can also set the click listener inside onBindViewHolder without using any interface by setting the click listener on parent view of your item_exercise_aud layout like this:

holder.parentView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, ViewExercise.class);
            intent.putExtra("image_id", exerciseList.get(position).getImage_id());
            intent.putExtra("name", exerciseList.get(position).getName());
            intent.putExtra("sanskrit_name", exerciseList.get(position).getSanskrit_name());
            intent.putExtra("eng_aud_url", exerciseList.get(position).getEng_aud_url());
            intent.putExtra("hindi_aud_url", exerciseList.get(position).getHindi_aud_url());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    });

Or you can refer here

Edit – To play the audio according to the recyclerview list’s position, we have to send the raw file name of that particular exercise to the media player.

Add two new variables to ExerciseAudio model class:

private String file_name_eng;
private String file_name_hindi;

Now modify the initData method as below:

private void initData() {

    exerciseList.add(new ExerciseAudio(R.drawable.sample_one, "Sample Exercise One", "Sans One",
            R.raw.sample_one_eng, R.raw.sample_one_hindi,
            "sample_one_eng", "sample_one_hindi"));

    exerciseList.add(new ExerciseAudio(R.drawable.sample_two, "Sample Exercise Two", "Sans Two",
            R.raw.sample_two_eng, R.raw.sample_two_hindi,
            "sample_two_eng", "sample_one_hindi"));

    exerciseList.add(new ExerciseAudio(R.drawable.sample_three, "Sample Exercise Three", "Sans Three",
            R.raw.sample_three_eng, R.raw.sample_three_hindi,
            "sample_three_eng", "sample_three_hindi"));

    exerciseList.add(new ExerciseAudio(R.drawable.sample_four, "Sample Exercise Four", "Sans Four",
            R.raw.sample_four_eng, R.raw.sample_four_hindi,
            "sample_four_eng", "sample_four_hindi"));
}

Now Modify the ViewExercise intent as:

intent.putExtra("file_name_eng", exerciseList.get(position).getFile_name_eng());
intent.putExtra("file_name_hindi", exerciseList.get(position).getFile_name_hindi());

Get the string extras in ViewExercise activity and send it to the mediaplayer:

file_name_eng = getIntent().getStringExtra("file_name_eng");
file_name_hindi = getIntent().getStringExtra("file_name_hindi");

For english:
    int resId = getResources().getIdentifier(file_name_eng, "raw", getPackageName());

For hindi:
    int resId = getResources().getIdentifier(file_name_hindi, "raw", getPackageName());
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..