Android code snippets

Below are some code Android code snippets, Android Studio, which maybe of use:-
Set textview color in code :-
TextView txt_vw;
txt_vw.setTextColor(ContextCompat.getColor(activity,R.color.colorRad));
Spinner :-
// find the spinner ....
Spinner spindecs = (Spinner) findViewById(R.id.spn_animate);
// using a array string  .... from the strings.xml file
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(activity,
        R.array.footy_options, R.layout.spinner_txt_2);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spindecs.setAdapter(adapter);
// setting the selected item change event
spindecs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override    public void onItemSelected(AdapterView<?> arg0, View arg1,
                               int arg2, long arg3) {
        str_animate = arg0.getSelectedItem().toString().toLowerCase(Locale.US);
        populate(str_animate);
        b_startup = false;
    }





    //@Override    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }
});
// setting the Adapter to a ArrayList :-
ArrayAdapter adp1 = new ArrayAdapter<>(activity,R.layout.spinner_txt_1, ArrayList_name);
// Button click events
Button btn = (Button) findViewById(R.id.btn_settings);
btn.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        btn_settings();
    }
});
Button btn = (Button) rootView.findViewById(R.id.btn_settings);
btn.setOnClickListener(new View.OnClickListener() {
    @Override    public void onClick(View v) {
        btn_settings();
    }
});
Spinner set color text size,colour etc ....
// create a layout i.e spinner_txt_2 and reference it when setup arrayadapter as above
<?xml version="1.0" encoding="utf-8"?><TextView    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:textSize="@dimen/txt_hd_size"    android:gravity="left"    android:textColor="@color/colorspinner"    android:padding="0dip"    android:id="@android:id/text1"    />
Number Picker size/colour
//setting textsize etc of numberpicker using a theme 
//scaleX,scaleY can be used to alter size .... 
<NumberPicker android:layout_width="0dip" android:layout_weight="0.4" android:layout_height="@dimen/num_pick_height" android:id="@+id/num_high" android:solidColor="#56B8FF" android:theme="@style/AppTheme.Picker" />
//styles.xml
<style name="AppTheme.Picker" parent="Theme.AppCompat.Light.NoActionBar" >
    <item name="android:textColorPrimary">@color/colorwhite</item>
    <item name="android:textSize">@dimen/num_pick_txt</item>
    <item name="android:background">@color/colorBlack</item>
</style>
Requesting permission
@Overridepublic void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {

        case REQUEST_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.            if (grantResults.length > 0                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
              // now run the procedure etc ....

            } else {
            }
            break;
        }
    }
}
Product Flavours with buildconfigfields:-
//build.gradle file
productFlavors {
    Apppredpro {
        applicationId = "com.xzy.www.xyz"        buildConfigField "boolean", "PAID_VERSION", "true"        buildConfigField "String", "DB_NAME", '"cfgh"'
    }
//in code
if(!BuildConfig.PAID_VERSION){
    Toast.makeText(activity, "This is the free version. For a low price,Please purchase the Full version from Google Play Store.", Toast.LENGTH_SHORT).show();
}
Arrays:-
String str_vals[] = new String[n];
ArrayList<String> array_name = new ArrayList<String>();
Content Values:-
import android.content.ContentValues;
ContentValues values = new ContentValues();
use :- values.put("id_game", str_rstxt[1]);


Examples of items to build.gradle etc in Adding Mobile Ads ....
AppBrain
//in build gradle 
buildscript {
    repositories {
        jcenter()
        maven {
            url 'http://swisscodemonkeys.github.io/appbrain-sdk/maven'
        }
        mavenCentral()
    }
    dependencies {
        classpath 'com.appbrain:appbrain-applift-sdk:+'
    }
}
// proguard 
# AppBrain SDK:-keep public class com.appbrain.KeepClass
-keep public class * implements com.appbrain.KeepClass
-keepclassmembers class * implements com.appbrain.KeepClass {
    <methods>;}
Adcolony
// in build.gradle
compile 'com.adcolony:sdk:3.1.2'
compile 'com.android.support:support-annotations:24.2.1'

//proguard
# For communication with AdColony's WebView -keepclassmembers class * {
     @android.webkit.JavascriptInterface <methods>; }
#For removing warnings due to lack of Multi-Window support
-dontwarn android.app.Activity
Amazon
// in build.gradle atleast
compile 'com.google.android.gms:play-services-ads:9.4.0'
compile 'com.google.android.gms:play-services-gcm:9.4.0'
compile 'com.amazon.android:mobile-ads:5.+'

//proguard
-dontwarn com.amazon.**
-keep class com.amazon.** {*;}
-keepattributes *Annotation*
KSoap2 -
using ksoap to connect to webservice.
// in build.gradle
compile 'com.google.code.ksoap2-android:ksoap2-android:3.6.1'
//in build gradle 
allprojects {
    repositories {
maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
}
//proguard..
-ignorewarnings-keep class org.kobjects.** { *; }
-keep class org.ksoap2.** { *; }
-keep class org.kxml2.** { *; }
-keep class org.xmlpull.** { *; }
//java file
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

... in code ....
private static String NAMESPACE = "http://www.xyz.com/webservices/";
private static String URL = "http://www.xyz.com/service.asmx";
private static String SOAP_ACTION = "http://www.xyz.com/webservices/GetXYZ";
... in code ....

SoapObject request = new SoapObject(NAMESPACE, webMethName);
// Setup Property holds input parameters
PropertyInfo p_info = new PropertyInfo();
// Set Namep_info.setName("icase");
// Set Valuep_info.setValue(db_ver);
// Set dataTypep_info.setType(ArrayList.class);
request.addProperty(p_info);
// Create envelopeSoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
        SoapEnvelope.VER11);
//Set envelope as dotNetenvelope.dotNet = true;
envelope.setOutputSoapObject(request);
resTxt = "Creating Call ...";
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
    // Invoke web service    resTxt = "Connecting ....";
    androidHttpTransport.call(SOAP_ACTION, envelope);
    resTxt = "Retrieved Data ....";
    SoapObject response = (SoapObject) envelope.bodyIn;
    resTxt = "Begin Process ....";
    SoapObject nameResult = (SoapObject) response.getProperty(0);
    int count = nameResult.getPropertyCount();

// loop thru the retrieved string ...
    if(count > 0) { 
        for (int i = 0; i < count - 1; i++) {
            //do whatever required next. in this example replace separator and then split. Could have split,depends on the retreived data
            resTxt = nameResult.getProperty(i).toString().replace("|^|", "*");
            str_rstxt = resTxt.split("\\*");
        }
    }else{
        resTxt = "No Data to Update ....!";
        return resTxt;
    }
    // Get the response    //    SoapPrimitive response = (SoapPrimitive) envelope.getResponse();    // Assign it to resTxt variable static variable   // arrdbversion.clear();    //    arrdbversion = response.toString();
} catch (Exception e) {
      e.printStackTrace(); }

Yeah, I've built a few apps along the way. You may find them useful. My official site is : chemistry chemical engineer solvers equations lotto android sports sudoku

Education/Profession based (Engineering,Chemistry,Maths,Unit Conversion....):- : -
chemistry chemical engineer solvers equations  Chemical Engineering Data Plus  Engineering Tools  Unit Conversions Engineering, General  Maths Linear Equations Solvers Plus

Health and Nutrition:-
 Nutrition and Health  Health maintain records
Sports:-
 Tennis game scorer and keeper  Aussie Rules predictor, team stats, year fixture,ladder updated per round  Racquet games scorer and keeper  Table Tennis game scorer and keeper  Badminton game scorer and stats keeper  Squash Game scorer and stats keeper
Games/Lotto :-
 Sudoku games Plus  Random Number Generator Plus  Pay Time monitor what you make every minute
onLine Radio :-
 onLine Radio world wide stations
Windows Applications(Engineering,Chemistry,Maths,Unit Conversion....):-
 ChemMaths for Windows  DataPro for Windows. Chemistry,Chemical Engineering Data.  EquationsPro for Windows.   GraphsProSim for Windows.  ChemPlayer. Media player for Windows.

Comments

Popular Posts