Inserting a value into a URL in android studio? - java

I sent data from Activity A to Activity B through means of an intent.
I then extracted the results of the intent via the following.
String IdString = questionData.getString("id");
TextView mstudentId = (TextView) findViewById(R.id.ID);
mstudentId.setText(IdString);
I would now like to take the value of IdString which is equal to the value of the string "id" and place it inside a Url. For example,
final static String URL_ANSWER = "http//:myFake/(IdString)/Url"
How do I go about doing this in Android Studio?

Like this,
final static String URL_ANSWER = "http//:myFake/" + IdString + "/Url";
OR
UPDATE
String IdString = questionData.getString("id");
TextView mstudentId = (TextView) findViewById(R.id.ID);
mstudentId.setText(IdString);
final static String URL_ANSWER = "http//:myFake/" + mstudentId.getText() + "/Url";

Related

Trying to pull plain text data to use in a service

I'm creating an app for an android mobile computer that can take the data scanned and convert a specified character to another. The way it currently works, I manually code in what characters to look for and convert to:
public String specialWorkFor(String originalData, String codeType ){
String[] targetStr = {"1", "2", "3"};
String[] replaceStr = {"a","b","c"};
String newData = "";
newData = originalData;
newData = ReplaceText(originalData,targetStr,replaceStr);
return newData;
}
private static String ReplaceText (String originalData, String[] targetStr, String[] replaceStr ){
String newData = "";
String newDataTmp = "";
newData = originalData;
for (int i = 0; i < targetStr.length; i++){
newDataTmp = newData.replace(targetStr[i], replaceStr[i]);
newData = newDataTmp;
}
return newData;
}
This works fine, but ideally I'd like to have an interface where I can just type into a plain text field and use the values from there to determine what characters get converted.
After creating the layout, I've tried doing this:
//Inputs
Context context1 = getApplicationContext();
Activity act1=(Activity)context1;
EditText codein = (EditText) act1.findViewById(R.id.input);
String in = codein.getText().toString();
//Outputs
Context context2 = getApplicationContext();
Activity act2=(Activity)context2;
EditText codeout = (EditText) act2.findViewById(R.id.output);
String out = codeout.getText().toString();
public String specialWorkFor(String originalData, String codeType ){
//String[] targetStr = {in};
//String[] replaceStr = {out};
String newData = "";
newData = originalData;
newData = ReplaceText(originalData,targetStr,replaceStr);
return newData;
}
Where I use:
Context context1 = getApplicationContext();
Activity act1=(Activity)context1;
EditText codein = (EditText) act1.findViewById(R.id.input);
String in = codein.getText().toString();
to pull values from the activity where I enter in my values. Issue is when I scan I get the error:
Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
I am unsure where to go from here. Any thoughts?
You cannot cast application context to an activity.
Create class Storage like this:
public class Storage {
public static final Storage instance = new Storage();
public String codeIn = "";
public String codeOut = "";
}
Add a textWatcher to both edittexts, and inside ontextchanged add :
Storage.instance.codeIn = whatever is in coresponding edittext
Inside the service you can get those values the same way:
String in = Storage.instance.codeIn
Also note that those values mast be set before the service uses them)))

Getting text from a spinner in android studios

I have a spinner with 2 selections, "text1" and "text2". When I tried to get "text1" and log "text1" to see if I got it or not, I got this instead: "androidx.appcompat.widget.AppCompatSpinner{d963757 VFED..CL. ........ 389,1177-883,1230 #7f080094 app:id/spinner1}".
What am I doing wrong?
String getSpinnerName = "spinner" + "1";
Spinner spinner = (Spinner) findViewById(getResources().getIdentifier(getSpinnerName, "id", getPackageName()));
final String spinnerText = spinner.toString();
Log.d(String.valueOf(LOG), spinnerText);
you are converting an object into String that's why.
final String spinnerText = spinner.toString();
if you want to get the values from spinner use below one.
final String spinnerText = spinner.getSelectedItem().toString();

Mediastore albums and media columns

Too retrieve the album id i use:
String SONG_ALBUMID = MediaStore.Audio.Albums.ALBUM_ID;
But what is the difference between MediaStore.Audio.Albums.ALBUM_ID and MediaStore.Audio.Media.ALBUM_ID
Thanks,
MediaStore.Audio.Albums.ALBUM_ID is the album id from the albums table and
MediaStore.Audio.Media.ALBUM_ID will be the "foreign key" album_id in the files table.In general relational database design is such that when accessing the files table, all we need is the abum_id to access the albums table and retrieve all relevant albums info such as album_title.The table files in the android database holds lots of details
eg
_id INTEGER
_data TEXT
_size INTEGER
format INTEGER
parent INTEGER
date_added INTEGER
date_modified INTEGER
mime_type TEXT
title TEXT
description TEXT
_display_name TEXT
picasa_id TEXT
orientation INTEGER
latitude DOUBLE
longitude DOUBLE
datetaken INTEGER
mini_thumb_magic INTEGER
bucket_id TEXT
bucket_display_name TEXT
isprivate INTEGER
title_key TEXT
artist_id INTEGER
album_id INTEGER
composer TEXT
track INTEGER
year INTEGER
is_ringtone INTEGER
is_music INTEGER
is_alarm INTEGER
is_notification INTEGER
is_podcast INTEGER
album_artist TEXT
duration INTEGER
bookmark INTEGER
artist TEXT
album TEXT
resolution TEXT
tags TEXT
category TEXT
language TEXT
mini_thumb_data TEXT
name TEXT
media_type INTEGER
old_id INTEGER
storage_id INTEGER
is_drm INTEGER
width INTEGER
height INTEGER
Here are 2 approaches:
(include the requested columns in your resolver.query)
public String getalbum_id(Cursor pcursor) {
int album_col = pcursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
String album_id = pcursor.getString(album_col);
if (album_id.length() > 0) {
return album_id;
} else {
return "";
}
}
public String getAlbumIdfromPath(Context context, String datapath) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String path = MediaStore.Audio.Media.DATA;
final String album_id = MediaStore.Audio.Media.ALBUM_ID;
final String[] columns = {_id, album_id};
final String[] trackpath = {"%" + datapath + "%"};
String where = path + " LIKE ?";
String stralbum_id = null;
Cursor crs = cr.query(uri, columns, where, trackpath, null);
if (crs != null && crs.moveToFirst()) {
stralbum_id = crs.getString(crs.getColumnIndexOrThrow(album_id));
crs.close();
}
return stralbum_id;
}
now to display, I have posted previously but I use the Gilde library. It does all the hard work.
// loading album cover using Glide library
String artist_id = (c.getString(c
.getColumnIndex(MediaStore.Audio.Artists._ID)));
Cursor albs = albums.getArtistsAlbumcursor(mContext, artist_id);
String stralbumId=null;
if(albs!=null && albs.moveToFirst()){
stralbumId= albs.getString(albs.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
Uri ImageUrl = plist.getAlbumUri(mContext, stralbumId);
if (ImageUrl != null) {
Glide.with(mContext)
.asBitmap()
.load(ImageUrl)
.into(image);
}
}
where getAlbumuri is:
public Uri getAlbumUri(Context mContext,String album_id){
if(mContext!=null) {
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri imageUri = Uri.withAppendedPath(sArtworkUri, String.valueOf(album_id));
return imageUri;
}
return null;
}
Include the following in your module build.gradle
implementation 'com.github.bumptech.glide:glide:4.5.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
private final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

What I missing when tried to retrieve data from Shared Preferences

Hey guyz check it out what I am missing here cause of I am not able to fetch all my data from Shared Preferences.
I am making such an tasklist application in which I am saving my data(means mytask) with a certain key and storing it in the shared Preferences and increments a variable for total count.
Check my Code(Whenever I click on addTask button the following code gets executed).
private void saveToSharedPreference(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
editor = sharedPre.edit();
String myKey = "key"+a;
String myValue = et.getText().toString();
editor.putString(myKey,myValue);
// editor.putInt("totalTask", a);
editor.commit();
}
Now when I close the application and open it again the following code gets executed in order to load the data from shared preferences.
private void loadData(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"+p;
while(sharedPre.getString(myKey,"") != null){
Toast.makeText(this, sharedPre.getString(myKey,""),Toast.LENGTH_SHORT).show();
}
}
but the problem is all it always returning null on all indexes. I don't know why I am getting this error. Please help me
Thanks in advance
Sarosh Madara
to load all saved values just use the following code:
private void loadData() {
SharedPreferences sharedPre = getSharedPreferences("todoPref",android.content.Context.MODE_PRIVATE);
Map<String,?> keys = sharedPre.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
if (entry.getValue().toString().length() > 0) {
Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());
}
}
}
I found it here but added a check to ignore null values.
to save values to Shared Preference I suggest using an instance of the current time for the key. no need to save any integer key values:
private void saveToSharedPreference(String myValue){
SharedPreferences sharedPre = getSharedPreferences("todoPref",android.content.Context.MODE_PRIVATE);
Editor editor = sharedPre.edit();
String key = String.valueOf(Calendar.getInstance().getTimeInMillis());
editor.putString(key,myValue);
editor.commit();
}
so whenever you want to add values to Shared Preferences use:
saveToSharedPreference("myValue");
and to load them all use:
loadData();
The Map Interface
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. read more...
SharedPreferences: Class Overview
Do like this -
1) save in shared preference like this -
private void saveToSharedPreference(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
editor = sharedPre.edit();
String myKey = "key"; // removed +a
String myValue = et.getText().toString();
editor.putString(myKey,myValue);
// editor.putInt("totalTask", a);
editor.commit();
}
2) load it like this -
private void loadData() {
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"; // removed "+p"
String value = sharedPre.getString(myKey, "");
}
Don't compare with != null in while loop. Use below code and see if the problem solves:-
private void loadData(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"+p;
String value = sharedPre.getString(myKey,"");
if(!value.equalsIgnoreCase("")){
Toast.makeText(this, sharedPre.getString(myKey,""),Toast.LENGTH_SHORT).show();
}
}

Android crashes when try to overwrite TextViews

I've created a timetable app, which allows the user to enter data and then view it.However if the user enters an entry, on a day and time where there already is one, my emulator crashes(forces a close).
Basically I'm pulling back data to a linear layout- which contains 10 TextViews, each representing the times 9-15.
Here's the code:
public void addMondayGrid() {
// TODO Auto-generated method stub
for (int index = 0; index < info.mon.size(); index++) {
// int entryId = info.monIds.get(index);
int time = info.monTimes.get(index);
int id = info.monIds.get(index);
int duration = info.monDuration.get(index);
String dayOfWeek = "mon";
timeId = getResources().getIdentifier("mon" + time, "id",
getPackageName());
if (duration == 1) {
SpannableString text = new SpannableString(info.mon.get(index));
setEntryColour(text);
final TextView textV = (TextView) findViewById(timeId);
textV.setTextSize(10);
textV.setText(text, BufferType.SPANNABLE);
textV.setId(id);
deleteGridEntry(textV);
} else {
longerDuration(time, index, id, info.mon, dayOfWeek);
}
}
}
The thing is is works fine as long as there isn't two entries for the same day and time, eg. monday at 9 oclock.
Anyone have any ideas?I'm quite new to this and any help would be much appreciated!
I have to reference the id this way as there are too many ids to reference any other way,is there not a simple way to overwrite the old textView with new data pulled back from the database? I want the id to be the same one as that is the textView I want to deal with, but it just keeps crashing, is it something to do with instances?
change:
final TextView textV = (TextView) findViewById(timeId);
to:
final TextView textV = (TextView) findViewById(R.id.timeId);

Categories

Resources