Friday, August 25, 2017

Swift: Load JSON data from Web and Parse it

Download This Example Code Here.
 

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad()
    {
        super.viewDidLoad()

        //let url = URL(string: "http://api.fixer.io/latest")
        let url = URL(string: "http://arkayapps.com/sellapp/edumcq/service/getchapterbysubject.php?subjectid=42");
        
        let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
            if error != nil
            {
                print ("ERROR")
            }
            else
            {
                if let content = data
                {
                    do
                    {
                        //Array
                        let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                        
                        print(myJson)
                            for index in 0...myJson.count-1 {
                                 let aObject = myJson[index] as! [String : AnyObject]
                                let chaptername = aObject["chaptername"] as! String
                                let chpid:Int? = Int(aObject["chapterid"] as! String)
                                let subid:Int? = Int(aObject["subjectid"] as! String)
                                
                                var chapter = Chapter(mark: chaptername, mycheptoriD: chpid!,mySubjectid: subid!)
                                print(chapter.chaptername)
                                print(chapter.chapterid)
                                print(chapter.subjectid)

                                
                        }
                        
                        
 
                    }
                    catch
                    {
                        
                    }
                }
            }
        }
        task.resume()
    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    struct Chapter {
        var chaptername: String
        var chapterid: Int
        var subjectid: Int
        
        init(mark: String, mycheptoriD: Int, mySubjectid: Int) {
            self.chaptername = mark
            self.chapterid = mycheptoriD
            self.subjectid = mySubjectid
        }
        
    }


}

Wednesday, August 2, 2017

Parsing JSON Array to Java ArrayList

First Create Bean Class that you need to convert on ArrayList. Right now for sample i have just create country Class as below.
 

public class Country {
    private int countryID;
    private String countryName;


    public Country(int countryID, String countryName) {
        this.countryID = countryID;
        this.countryName = countryName;
    }

    public int getCountryID() {
        return countryID;
    }

    public void setCountryID(int countryID) {
        this.countryID = countryID;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

}

Now lets Create Json String for convert Java ArrayList Object. This string also come from JSON API.
    private String countryJson = "{\"category\": [{\n" +
            "            \"countryID\":\"1\",\n" +
            "            \"countryName\": \"India\",\n" +
            "            {\n" +
            "            \"countryID\": \"2\",\n" +
            "            \"countryName\": \"UK\",\n" +
            "            },\n" +
            "            {\n" +
            "            \"countryID\": \"3\",\n" +
            "            \"countryName\": \"US\",\n" +
            "            \n" +
            "            }\n" +
            "            ]\n" +
            "            }";

         Type listType = new TypeToken>() {}.getType();

        JsonParser jsonParser = new JsonParser();
        JsonObject jo = (JsonObject)jsonParser.parse(countryJson);
        JsonArray jsonArr = jo.getAsJsonArray("category");
        Gson googleJson = new Gson();
        countries = googleJson.fromJson(jsonArr.toString(), listType);

        System.out.println("List Elements are  : "+countries.get(0).getCountryName());

That's it.

Saturday, July 15, 2017

NSNotificationCenter is Communication tools internal to your app

In App Development some time we need internal communication to pass message to one ViewController to other ViewController. As Example. I am using Google login using Firebase now login task doing AppDelegate Now i need message when login success or fail on ViewController.  Then here we can use NSNotificationCenter.

1. Create Globally define a"Special Notification Key" constant that can be broadcast. on ViewController

   let mySpecialNotificationKey = "com.arkay.specialNotificationKey" 


2. Set Observer on ViewController.
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateNotificationSentLabel), name: NSNotification.Name(rawValue: mySpecialNotificationKey), object: nil)

3. Create Func that can call when Notify ViewController

 func updateNotificationSentLabel(){
        btnSignIn.setTitle("Login Out",for: .normal)
    }]

4. Now Call When need. Right now i am calling from AppDelegate.

        NotificationCenter.default.post(name: Notification.Name(rawValue: mySpecialNotificationKey), object: self)


That's it.

Friday, July 14, 2017

Getting start with CocoaPods iPhone app Using XCode.

As you know without lib it's to difficult to completed project. In Android we use Gradle  as Dependency manager but in Swift and Objective-c it's CocoaPods is Dependency Manager. This tutorial will explain how to getting start with CocoaPods on XCode.

1. Create iPhone new project using XCode.
2. Now Close this Project.
3. Execute Following command.
sudo gem install cocoapods



4.  Open Terminal and goes on your Project location.
cd ~/Desktop/CocoapodsTestApp
 
5.  Now Simple Execute following command.
pod init
 
6. Now check project location it will be generate PodFile.


7. Open that Pod File on Text Editor It will be look like below.

8. Now you can add as my POD at # Sing. Let's try add Firebase Pod There.


9.  Now Save this file. 
10. And Execute following command same as project location.
pod install



11.  its done.. Thanks..
12. Now Open xcode Proejct. Be CAREFUL when open .xcworkspace file not .xcodeproj

Thanks. 









Monday, September 12, 2011

Blackberry Color Label Field

Following code example use for create custom color label filed.


import net.rim.device.api.i18n.ResourceBundleFamily;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.LabelField;

public class ColorLableField extends LabelField{
private int color = 0x000000;
public ColorLableField(String text){
super(text);
}
public ColorLableField(Object text, int offset, int length, long style){
super(text, offset, length, style);
}
public ColorLableField(Object text, long style){
super(text, style);
}
public ColorLableField(ResourceBundleFamily rb, int key){
super(rb, key);
}

//Set the color of the text in this field
public void setColor(int newColor){
color = newColor;
}

//Set the foreground color and then call paint method of the parent class
public void paint(Graphics graphics){
graphics.setColor(color);
super.paint(graphics);
}
}

public final class MyScreen extends MainScreen{

public MyScreen()
{
setTitle("MyTitle");
ColorLableField lbl = new ColorLableField("this is text");
lbl.setColor(Color.RED);
this.add(lbl);
}
}

Monday, August 1, 2011

Call RSS Feed In android

Here Example of Call RSS Feed in android application or Java.
public void writeNews() {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
URL u = new URL("http://www.itpro.co.uk/blogs/feed/"); // your feed url
Document doc = builder.parse(u.openStream());
NodeList nodes = doc.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
System.out.println("Title: " + getElementValue(element, "title"));
System.out.println("Link: " + getElementValue(element, "link"));
System.out.println("Publish Date: " + getElementValue(element, "pubDate"));
System.out.println("Author: " + getElementValue(element, "dc:creator"));
System.out.println("Description: " + getElementValue(element, "description"));
System.out.println();
}//for
}//try
catch (Exception ex) {
ex.printStackTrace();
}
}

private String getCharacterDataFromElement(Element e) {
try {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
} catch (Exception ex) {
}
return "";
} //private String getCharacterDataFromElement

protected float getFloat(String value) {
if (value != null && !value.equals("")) {
return Float.parseFloat(value);
} else {
return 0;
}
}

protected String getElementValue(Element parent, String label) {
return getCharacterDataFromElement((Element) parent.getElementsByTagName(label).item(0));
}

Friday, July 1, 2011

One difference between implementing Runnable and extending Thread is that by extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same Object instance. for example.


public class Main {

   public static void main(String[] args) {
     RunnableThread r = new RunnableThread();
     Thread t1 = new Thread(r, "Thread A");
     Thread t2 = new Thread(r, "Thread B");
     ExtendsThread t3 = new ExtendsThread("Thread C");
     ExtendsThread t4 = new ExtendsThread("Thread D");
     t1.start();
     t2.start();
     t3.start();
     t4.start();

   }
 }



class RunnableThread implements Runnable {

private int counter;

  public void run() {
   try {
     for (int i = 0; i != 2; i++) {
   System.out.println(Thread.currentThread().getName()+ ":"counter++);
      Thread.sleep(1000);
      }
    } catch (InterruptedException ine) {
    System.err.println(ine);
   }
 }
}

class ExtendsThread extends Thread {
  private int counter;
  ExtendsThread(String name) {
  super(name);
 }

 @Override
 public void run() {
  try {
   for (int i = 0; i != 2; i++) {
   System.out.println(Thread.currentThread().getName() + ": "+ counter++);
   Thread.sleep(1000);
   }
  } catch (InterruptedException ine) {
   System.err.println(ine);
 }
 }
}

Thursday, June 30, 2011

9 ways to improve your programming skills.

1. Learn a new programming language.
2. Read a good, challenging programming book.
Like: The Art of Computer Programming
Structure and interpretation of computer Programs.
A Discipline of Programming
3. Join an Open Source Project.
You Can join: GitHub, SourceForge,gitorius, bitBucket, Ohloh
4. Solve Programming puzzles.
5. Program Start writing a program. scratch. design all of the architechture and implement.
6. Read And Study Code.
7. Hang Out as programming sites and read blogs.
8. Write about coding.
9. learn low level programming like C, Assembly language.

JUnit Test Case with Example.

Here is Sample example on Junit Text Case.

Let's Test Some Code

public class Main {

public static void main(String[] args) {
}
static public int add(int a, int b) {
return a + b;
}

}


now i want to test about class using Junit Test case. fot test we require to import "junit.framework.*" and extend TestCase

import junit.framework.*;
public class TestMaths extends TestCase{

public void testMaths() {
int num1 = 2;
int num2 = 3;
int total = 5;
int sum = 0;
sum = Main.add(num1, num2);
assertEquals(sum, total);
}
}


Here i am using Netbeans. now run TestMaths file you can see out put on console.

Summary:
That's it! This example may be help full to getting start JUnit.

enjoy!

Tuesday, June 21, 2011

Android Flip View Example

Here i try to explain Android Flip View. Flip View is use to flip one view to another with use android set of animation.

Create Following Activity FlipeActivity.java file
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ViewFlipper;

public class FlipeActivity extends Activity {
ViewFlipper flipper;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
flipper=(ViewFlipper)findViewById(R.id.details);
flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in));
flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out));
Button btn=(Button)findViewById(R.id.flip_me);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
flipper.showNext();
}
});

}


}

we load here Animation xml file so we create first "anim" folder and create following file with set.
push_left_in.xml
xmlns:android="http://schemas.android.com/apk/res/android">
android:fromXDelta="100%p" android:toXDelta="15" android:duration="500"/>


push_left_out.xml
xmlns:android="http://schemas.android.com/apk/res/android">
android:fromXDelta="0" android:toXDelta="-100%p" android:duration="500"/>

main.xml
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

you can find more animation set here with example..
http://code.google.com/p/android-helloworld-samples/source/browse/trunk/ApiDemos/res/anim/

Monday, June 20, 2011

Android Services Example

Create Following Class for Services.

import android.app.Service;
import android.content.Intent;

import android.os.IBinder;
import android.util.Log;


public class MyServices extends Service{
private static final String TAG = MyServices.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"MyServices Created");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(TAG,"MyServices Started");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG,"MyServices Destroyd");
}

}

Register Services in AndroidManifest.xml file.

service android:name=".MyServices"


Call(Start) Services in Activity.

startService(new Intent(this,MyServices.class));

Blackberry Contact Event Handling.

Blackberry Contact Event Handling.

import java.util.Enumeration;
import java.util.Enumeration;
import javax.microedition.pim.Contact;
import javax.microedition.pim.ContactList;
import javax.microedition.pim.PIMItem;
import javax.microedition.pim.PIMList;
import net.rim.blackberry.api.pdap.PIMListListener2;

final class MyPIMListener implements PIMListListener2 {
public void itemAdded(PIMItem item) {
if (item == null) {
return;
}
}

public void itemRemoved(PIMItem item) {
if (item == null) {
return;
}
}

public void itemUpdated(PIMItem oldItem, PIMItem newItem) {
if (oldItem == null || newItem == null) {
return;
}
itemRemoved(oldItem);
itemAdded(newItem);
}

public void batchOperation(PIMList list) {
if (list == null) {
return;
}
try {
ContactList contactList = (ContactList) list;
Enumeration e = contactList.items();
while (e.hasMoreElements()) {
Contact contact = (Contact) e.nextElement();
// ...
}
} catch (Exception e) {
// ...
}
}
}

Wednesday, June 15, 2011

Start android application on when Device start Or Boot Startup

Create MyBootStartUpListener.java in.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class MyBootStartUpListener extends BroadcastReceiver{
private static final String TAG = MyBootStartUpListener.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d(TAG, "My BootStartup");
try{
Intent homeIntent = new Intent(context,bootStartupActivity.class);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(homeIntent);
}catch(Exception e){
System.err.println(e);
}
Log.d(TAG, "My BootStartup succefully");
}

}



receiver android:name=".MyBootStartUpListener"
intent-filter
action android:name="android.intent.action.BOOT_COMPLETED"
category android:name="android.intent.category.HOME"
intent-filter
receiver

Android Notification Example

Hi This is you can add notification in android.

NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.notification_icon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();

Notification notification = new Notification(icon, tickerText, when);
CharSequence contentTitle = "Hello world";
CharSequence contentText = "Description";
Intent notificationIntent = new Intent(this, MyNoticiationActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
mNotificationManager.notify(KEEPUS_NOTIFICATION_ID, notification);

Sunday, June 12, 2011

Android Recipes and Snippets

Android Recipes and Snippets

I've put together a small collection of Android recipes. For each of these recipes, this is an instance of Context (more specifically, Activity or Service) unless otherwise noted. Enjoy :)

Intents
One of the coolest things about Android is Intents. The two most common uses of Intents are starting an Activity (open an email, contact, etc.) and starting an Activity for a result (scan a barcode, take a picture to attach to an email, etc.). Intents are specified primarily using action strings and URIs. Here are some things you can do with the android.intent.action.VIEWaction and startActivity().
Intent intent = new Intent(Intent.ACTION_VIEW);
// Choose a value for uri from the following.
// Search Google Maps: geo:0,0?q=query
// Show contacts: content://contacts/people
// Show a URL: http://www.google.com
intent.setData(Uri.parse(uri));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Other useful action/URI pairs include:
  • Intent.ACTION_DIAL, tel://8675309
  • Intent.ACTION_CALL, tel://8675309
More interesting things are available when you use startActivityForResult(). For example, to scan a barcode:
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
Then, add onActivityResult to your activity.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
Bundle extras = data.getExtras();
String result = extras.getStringExtra("SCAN_RESULT");
// ...
}
}
Taking a picture is done like so:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
// ...

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
// ...
}
}
Check out the OpenIntents registry for more information.

Wifi

The WifiManager can be used to enable and disable wifi. Where enabled is a boolean, it's as easy as:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(enabled);
Notifications
Text notifications (called Toast) which appear briefly above all activities are also easy:
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
You can increase the time the notification is displayed by using Toast.LENGTH_LONG instead.

Alert and Input Dialogs
Sometimes it's useful to prompt the user for input. An easy way to do that without creating a new layout is to useAlertDialog.Builder.
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(title);
alert.setMessage(message);

// You can set an EditText view to get user input besides
// which button was pressed.
final EditText input = new EditText(this);
alert.setView(input);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});

alert.show();
Location
Use the LocationManager to start up the GPS and listen for location updates.
LocationManager locator = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
location.getAltitude();
location.getLatitude();
location.getLongitude();
location.getTime();
location.getAccuracy();
location.getSpeed();
location.getProvider();
}
}

public void onProviderDisabled(String provider) {
// ...
}

public void onProviderEnabled(String provider) {
// ...
}

public void onStatusChanged(String provider, int status, Bundle extras) {
// ...
}
};

// You need to specify a Criteria for picking the location data source.
// The criteria can include power requirements.
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // Faster, no GPS fix.
criteria.setAccuracy(Criteria.ACCURACY_FINE); // More accurate, GPS fix.
// You can specify the time and distance between location updates.
// Both are useful for reducing power requirements.
mLocationManager.requestLocationUpdates(mLocationManager.getBestProvider(criteria, true),
MIN_LOCATION_UPDATE_TIME, MIN_LOCATION_UPDATE_DISTANCE, mLocationListener,
getMainLooper());
You can also get the phone's last known location using the LocationManager. This is faster than setting up aLocationListener and waiting for a fix.
// Start with fine location.
Location l = locator.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (l == null) {
// Fall back to coarse location.
l = locator.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
SMS
Sending a text is done with the SmsManager.
SmsManager m = SmsManager.getDefault();
String destination = "8675309";
String text = "Hello, Jenny!";
m.sendTextMessage(destination, null, text, null, null);
Vibrate
You can vibrate the phone for a specified duration like so:
(Vibrator) getSystemService(Context.VIBRATOR_SERVICE).vibrate(milliseconds);
Sensors
Accessing sensor data is done using the SensorManager.
SensorManager mSensorManager = (SensorManager) getSystemService(Activity.SENSOR_SERVICE);
private final SensorListener mSensorListener = new SensorListener() {
public void onAccuracyChanged(int sensor, int accuracy) {
// ...
}

public void onSensorChanged(int sensor, float[] values) {
switch (sensor) {
case SensorManager.SENSOR_ORIENTATION:
float azimuth = values[0];
float pitch = values[1];
float roll = values[2];
break;
case SensorManager.SENSOR_ACCELEROMETER:
float xforce = values[0];
float yforce = values[1];
float zforce = values[2];
break;
case SensorManager.SENSOR_MAGNETIC_FIELD:
float xmag = values[0];
float ymag = values[1];
float zmag = values[2];
break;
}
}
};

// Start listening to all sensors.
mSensorManager.registerListener(mSensorListener, mSensorManager.getSensors());
// ...
// Stop listening to sensors.
mSensorManager.unregisterListener(mSensorListener);
Silence Ringer
You can use the AudioManager to enable and disable silent mode.
mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
mAudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
// or...
mAudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);