0

Help me in finding the solution. Below is my code which does scanning and displays in text view, Now I want to save this text view in a any format.

Below is my code.

public class MainActivity extends AppCompatActivity {
TextView tv;
Button bt;
String contents="", format="";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView)findViewById(R.id.contents);
    bt = (Button)findViewById(R.id.save);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent in) {
    IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, in);
    if (scanningResult != null) {
        try {
            contents = in.getStringExtra("SCAN_RESULT");
            format = in.getStringExtra("SCAN_RESULT_FORMAT");
            tv.setText("Content-" + contents + "\n" + " Format-" + format);
        }
        catch (NullPointerException e){}
    }
}

public void save(View v){
    if(contents.equals("")){
        Toast.makeText(getApplication(),"Click Camera icon to Scan BarCode",Toast.LENGTH_LONG).show();
    }
    else{
        //search scan result on web
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(contents)));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);//Menu Resource, Menu
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_camera:
            IntentIntegrator scanIntegrator = new IntentIntegrator(MainActivity.this);
            scanIntegrator.initiateScan();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
}

How could I achieve this using shared preferences?

ganga
  • 5
  • 8
  • 1
    Possible duplicate of [Android - Storing/retrieving strings with shared preferences](https://stackoverflow.com/questions/12074156/android-storing-retrieving-strings-with-shared-preferences) – Agon Avdijaj May 03 '18 at 08:06
  • Thank you for the link. I will check it out :) – ganga May 03 '18 at 09:21

1 Answers1

0

To save a value to a SharedPrefence you do something like this:

private static final String PREF_KEY_SOMETHING = "PREF_KEY_SOMETHING";

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.edit().putString(PREF_KEY_SOMETHING, yourValue).apply();

To retrieve it again you do the following.

    String yourValueBack = sharedPreferences.getString(PREF_KEY_SOMETHING ,null);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459