Post data using json Android

( 1 ) Create Android Application

  • File >> New >> Android Application
  • App Name: POST JSON
  • Enter Project Name: android-post-json
  • Pakcage: com.hmkcode.android
  • Keep other defualt selections, go Next  till you reach Finish

( 2 ) The App Layout & Views

  • Main layout is LinearLayout
  • One TextView that shows connection status “the one in green”.
  • One child layout RelativeLayout holding data entry part.
  • Three TextViews “Name, Country & Twitter” baseline-aligned with their correspondingEditText
  • One Button to send “post” data to the server.
  • res/layout/activity_main.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:orientation=”vertical” >
 
    <TextView
        android:id=”@+id/tvIsConnected”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:layout_gravity=”center_horizontal”    
        android:background=”#FF0000″
        android:textColor=”#FFF”
        android:textSize=”18dp”
        android:layout_marginBottom=”5dp”
        android:text=”is connected?” />
 
   <RelativeLayout
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”>
 
       <TextView
            android:id=”@+id/tvName”
            android:layout_width=”50dp”
            android:layout_height=”wrap_content”
            android:text=”Name”
            android:layout_alignBaseline=”@+id/etName”/>
       <EditText
            android:id=”@+id/etName”
            android:layout_width=”150dp”
            android:layout_height=”wrap_content”
            android:layout_toRightOf=”@+id/tvName”/>
       <TextView
            android:id=”@+id/tvCountry”
            android:layout_width=”50dp”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/tvName”
            android:text=”Country”
            android:layout_alignBaseline=”@+id/etCountry”/>
       <EditText
            android:id=”@+id/etCountry”
            android:layout_width=”150dp”
            android:layout_height=”wrap_content”
            android:layout_toRightOf=”@+id/tvCountry”
            android:layout_below=”@+id/etName”/>
       <TextView
            android:id=”@+id/tvTwitter”
            android:layout_width=”50dp”
            android:layout_height=”wrap_content”
            android:layout_below=”@+id/tvCountry”
            android:text=”Twitter”
            android:layout_alignBaseline=”@+id/etTwitter”/>
       <EditText
            android:id=”@+id/etTwitter”
            android:layout_width=”150dp”
            android:layout_height=”wrap_content”
            android:layout_toRightOf=”@+id/tvTwitter”
            android:layout_below=”@+id/etCountry”/>
   </RelativeLayout>
 
   <Button
       android:id=”@+id/btnPost”
       android:layout_width=”200dp”
       android:layout_height=”wrap_content”
       android:layout_gravity=”center_horizontal”
       android:text=”POST”/>
 
</LinearLayout>

( 3 ) The Person Class

 

This is a simple model class to hold person information “name, country & twitter account”.

  • /src/com/hmkcode/android/vo/Person.java

 

package com.hmkcode.android.vo;
 
public class Person {
 
    private String name;
    private String country;
    private String twitter;
 
//getters & setters….
 
}

( 4 ) The Activity Class

  • onCreate()
    1. Get reference to the defined views in layout file
    2. Check for connection status
    3. Add click listener to the Post button
  • POST(url, Person)
      1. Open Http connection.
      2. Create HttpPOST object passing the url.
      3. Create Person object & convert it to JSON string.
      4. Add JSON to HttpPOST, set headers & send the POST request.
      5. Get the response Inputstream, convert it to String and return it.
  • HttpAsyncTask
    1. Helps in creating the connection in a separate thread so the UI will not freeze.
  • onClick
    1. This method is executed when user click on Post button
    2. It create HttpAsyncTask object and execute it.
  • isConnected()
    1. Check if there is network connection or not
  • validate()
    1. Helper method to check that data is not empty before send the request.
  • convertInputStreamToString()
    1. Helper method to convert inputstream to String
  • src/com/hmkcode/android/ActivityMain.java

package com.hmkcode.android;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;
 
public class MainActivity extends Activity implements OnClickListener {
 
    TextView tvIsConnected;
    EditText etName,etCountry,etTwitter;
    Button btnPost;
 
    Person person;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // get reference to the views
        tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
        etName = (EditText) findViewById(R.id.etName);
        etCountry = (EditText) findViewById(R.id.etCountry);
        etTwitter = (EditText) findViewById(R.id.etTwitter);
        btnPost = (Button) findViewById(R.id.btnPost);
 
        // check if you are connected or not
        if(isConnected()){
            tvIsConnected.setBackgroundColor(0xFF00CC00);
            tvIsConnected.setText(“You are conncted”);
        }
        else{
            tvIsConnected.setText(“You are NOT conncted”);
        }
 
        // add click listener to Button “POST”
        btnPost.setOnClickListener(this);
 
    }
 
    public static String POST(String url, Person person){
        InputStream inputStream = null;
        String result = “”;
        try {
 
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
 
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
 
            String json = “”;
 
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate(“name”, person.getName());
            jsonObject.accumulate(“country”, person.getCountry());
            jsonObject.accumulate(“twitter”, person.getTwitter());
 
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
 
            // ** Alternative way to convert Person object to JSON string usin Jackson Lib
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person);
 
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
 
            // 6. set httpPost Entity
            httpPost.setEntity(se);
 
            // 7. Set some headers to inform server about the type of the content   
            httpPost.setHeader(“Accept”, “application/json”);
            httpPost.setHeader(“Content-type”, “application/json”);
 
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
 
            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();
 
            // 10. convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = “Did not work!”;
 
        } catch (Exception e) {
            Log.d(“InputStream”, e.getLocalizedMessage());
        }
 
        // 11. return result
        return result;
    }
 
    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected())
                return true;
            else
                return false;    
    }
    @Override
    public void onClick(View view) {
 
        switch(view.getId()){
            case R.id.btnPost:
                if(!validate())
                    Toast.makeText(getBaseContext(), “Enter some data!”, Toast.LENGTH_LONG).show();
                // call AsynTask to perform network operation on separate thread
                new HttpAsyncTask().execute(“http://hmkcode.appspot.com/jsonservlet&#8221;);
            break;
        }
 
    }
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String… urls) {
 
            person = new Person();
            person.setName(etName.getText().toString());
            person.setCountry(etCountry.getText().toString());
            person.setTwitter(etTwitter.getText().toString());
 
            return POST(urls[0],person);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), “Data Sent!”, Toast.LENGTH_LONG).show();
       }
    }
 
    private boolean validate(){
        if(etName.getText().toString().trim().equals(“”))
            return false;
        else if(etCountry.getText().toString().trim().equals(“”))
            return false;
        else if(etTwitter.getText().toString().trim().equals(“”))
            return false;
        else
            return true;    
    }
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = “”;
        String result = “”;
        while((line = bufferedReader.readLine()) != null)
            result += line;
 
        inputStream.close();
        return result;
 
    }   
}

Note: do not forget to add the permissions to AndroidManifest.xml file

  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

( 5 ) Run & Check

  • Deploy the app and run it
  • Enter name, country & twitter
  • Click on “POST” button.
  • Wait for the “Data Sent!” message

Reference : http://hmkcode.com/android-send-json-data-to-server/

 

 

 

Is Android’s AsyncTask executing tasks serially or concurrently?

This post focuses on one method only and in the case of AsyncTask.execute() it’s certainly motivated. The execution behavior is often misunderstood and it’s not easy to know whether tasks will be executed serially or concurrently.

The Problem

AsyncTask is the most commonly used background execution technique on Android and for most use cases we want to know how execution of multiple tasks is performed. If the tasks utilize common resources, e.g. the file system, we probably want to simplify the handling by executing them serially. On the other hand, if we have multiple independent tasks we want to improve throughput by executing them concurrently. So, how should we know if the following code executes our tasks as expected:

Platform Level Differences

The main cause of confusion is that the behavior has changed over time and at first the changes were considered to be an internal implementation detail and not documented. The documentation improved in Honeycomb but still omits important information.

Before Donut:
The first versions of AsyncTask.execute() let all tasks execute serially., Hence, before a task can execute, all the previous tasks have to be finished. The problem with this approach is that tasks delayed each other and the throughput could be bad when many long running tasks were executed with the AsyncTask.

From Donut to Gingerbread:
To improve throughput the behavior of the AsyncTask was changed so that each task was executed on a separate thread. The problem with this was that many users had relied on the sequential behavior and now suddenly started to encounter concurrency issues. Even the Android platform suffered from this internally.

Honeycomb and onwards:
Execution was switched back to the sequential implementation and another method executeOnExecutor(Executor) was added if parallel execution was needed.

In conclusion this means that if our application cares about whether the tasks are executed serial or parallel we need to check in runtime what platform version we are executing on and define the execution accordingly.

The targetSdkVersion Caveat

With the knowledge described above of how AsyncTask.execute() has changed over time it seems safe to say that when I execute a task on Honeycomb or later platforms all tasks will be executed serially. Unfortunately, also the android:targetSdkVersion attribute set in the AndroidManifest.xml makes a difference.

The targetSdkVersion refers to the API level that your application targets. If not defined it’s set to minSdkVersion. Let us see why this has an impact for our use case by looking at two code extracts from AsyncTask.java and ActivityThread.java in Honeycomb:

The two code snippets above shows that as of Honeycomb the platform can change the default behavior of the execution environment in the AsyncTask in runtime and this is exactly what ActivityThread is doing. If we have set the targetSdkVersion lower than Honeycomb, AsyncTask.execute() will still execute tasks in parallel although we would expect serial execution. In clarity:

AsyncTask.execute() will execute tasks in parallel on Honeycomb and onwards.

AsyncTask.execute() will execute tasks serially on Honeycomb and onwards.

Unfortunately nothing concerning the impact of targetSdkVersion is mentioned in the documentation, but now you know 🙂

In practice, if we would like to execute all our tasks concurrently when targetSdkVersion is 13 or higher we need to do a runtime check to decide how to execute. For instance by a wrapper class (Pre-Donut not included):

If we on the other hand would like to execute tasks serially on all platforms after Donut the AsyncTask is unfortunately not to recommend, since it doesn’t have any serial execution behaviour between the Donut and Honeycomb versions. Instead the application should utilize a HandlerThread or Executors.newSingleThreadExecutor().

Reference : http://www.jayway.com/2012/11/28/is-androids-asynctask-executing-tasks-serially-or-concurrently/

Android Run Multiple AsyncTask Same Time

Android Run Multiple AsyncTask Same Time

Problem:
I am trying to excute Multiple asynctask same time(Android Version 4.0.1) but onPreExcute method only called  after that nothing happen.
 
Solution.
AsyncTask uses a thread pool pattern for running the stuff from doInBackground(). The issue is initially (in early Android OS versions) the pool size was just 1, meaning no parallel computations for a bunch of AsyncTasks. But later they fixed that and now the size is 5, so at most 5 AsyncTasks can run simultaneously. 
 
 

–> 

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

TestAsyncTask firstAsync = new TestAsyncTask();

firstAsync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

 

}

else{

TestAsyncTask firstAsync = new TestAsyncTask();

firstAsync.execute();

 

}

ZoomControls Android

 Static Zoom Controls Creation in Android

Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click “Finish” button. If you have any doubt regarding create a new project Click Here.

 

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :
 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    
    <TextView
        android:id="@+id/textView1"
        android:textSize="18dp"
        android:textColor="#4169E1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="Static ZoomControls" />
 
    <ZoomControls
        android:id="@+id/zoomControls1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="40dp" />
 
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_launcher" />
 
</RelativeLayout>
Step 3 : Open src -> package -> MainActivity.java and add following code :
 
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ZoomControls;
 
public class MainActivity extends Activity {
	
	ZoomControls zoom;
	ImageView img;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        zoom = (ZoomControls) findViewById(R.id.zoomControls1);
        img = (ImageView) findViewById(R.id.imageView1);
        
        zoom.setOnZoomInClickListener(new OnClickListener() {
			
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			float x = img.getScaleX();
			float y = img.getScaleY();
			
			img.setScaleX((float) (x+1));
			img.setScaleY((float) (y+1));
		}
	});
 
        zoom.setOnZoomOutClickListener(new View.OnClickListener() {
			
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
 
			float x = img.getScaleX();
			float y = img.getScaleY();
			
			img.setScaleX((float) (x-1));
			img.setScaleY((float) (y-1));
		}
	});
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
 
 Dynamic Zoom Controls Creation in Android
 
Step 1 : Select File -> New -> Project -> Android Application Project (or) Android Project. Fill the forms and click “Finish” button. If you have any doubt regarding create a new project Click Here.

Step 2 : Open res -> layout -> activity_main.xml (or) main.xml and add following code :
 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    
    <TextView
        android:id="@+id/textView1"
        android:textSize="18dp"
        android:textColor="#4169E1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="40dp"
        android:text="Dynamic ZoomControls" />
    
 
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_launcher" />
 
</RelativeLayout>
Step 3 : Open src -> package -> MainActivity.java and add following code :
 
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ZoomControls;
import android.widget.RelativeLayout.LayoutParams;
 
public class MainActivity extends Activity {
	
	RelativeLayout rl;
	ZoomControls zoom;
	ImageView img;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        rl = (RelativeLayout) findViewById(R.id.rl);
        img = (ImageView) findViewById(R.id.imageView1);
        
        zoom = new ZoomControls(MainActivity.this);
        
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams 
        		((int) LayoutParams.WRAP_CONTENT, (int) LayoutParams.WRAP_CONTENT);
        
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        params.bottomMargin = 40;
        
        zoom.setLayoutParams(params);
        
        rl.addView(zoom);
        
        zoom.setOnZoomInClickListener(new OnClickListener() {
			
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			float x = img.getScaleX();
			float y = img.getScaleY();
			
			img.setScaleX((float) (x+1));
			img.setScaleY((float) (y+1));
		}
	});
        
        zoom.setOnZoomOutClickListener(new View.OnClickListener() {
			
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			float x = img.getScaleX();
			float y = img.getScaleY();
			
			img.setScaleX((float) (x-1));
			img.setScaleY((float) (y-1));
		}
	});
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
 
 

Drag drop in Android

In DragDrop.java :

import android.app.Activity;

import android.os.Bundle;

import android.view.KeyEvent;

 

public class  DragDrop extends Activity {

    @Override

public boolean onKeyDown(int keyCode, KeyEvent event) {

// TODO Auto-generated method stub

    System.exit(0);

return super.onKeyDown(keyCode, event);

}

 

/** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        

        // draw the view

        setContentView(new DrawView(this));

        

        

    }

    

}

In colorball.java:

import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.Point;

 

public class ColorBall  {

 private Bitmap img; // the image of the ball

 privateintcoordX = 0; // the x coordinate at the canvas

 privateintcoordY = 0; // the y coordinate at the canvas

 privateintid; // gives every ball his own id, for now not necessary

 privatestaticintcount = 1;

 privatebooleangoRight = true;

 privatebooleangoDown = true;

 

public ColorBall(Context context, int drawable) {

 

BitmapFactory.Options opts = new BitmapFactory.Options();

        opts.inJustDecodeBounds = true;

        img = BitmapFactory.decodeResource(context.getResources(), drawable); 

        id=count;

count++;

 

}

 

public ColorBall(Context context, int drawable, Point point) {

 

BitmapFactory.Options opts = new BitmapFactory.Options();

        opts.inJustDecodeBounds = true;

        img = BitmapFactory.decodeResource(context.getResources(), drawable); 

        id=count;

count++;

coordX= point.x;

coordY = point.y;

 

}

 

public static int getCount() {

returncount;

}

 

void setX(int newValue) {

        coordX = newValue;

    }

 

public int getX() {

returncoordX;

}

 

void setY(int newValue) {

        coordY = newValue;

   }

 

public int getY() {

returncoordY;

}

 

public int getID() {

returnid;

}

 

public Bitmap getBitmap() {

returnimg;

}

 

public void moveBall(int goX, int goY) {

// check the borders, and set the direction if a border has reached

if (coordX > 270){

goRight = false;

}

if (coordX < 0){

goRight = true;

}

if (coordY > 400){

goDown = false;

}

if (coordY < 0){

goDown = true;

}

// move the x and y 

if (goRight){

coordX += goX;

}else

{

coordX -= goX;

}

if (goDown){

coordY += goY;

}else

{

coordY -= goY;

}

 

}

 

}

In DrawView.java:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.View;

public class DrawView extends View {
private ColorBall[] colorballs = new ColorBall[3]; // array that holds the balls
private int balID = 0; // variable to know what ball is being dragged

public DrawView(Context context) {
super(context);
setFocusable(true); //necessary for getting the touch events

// setting the start point for the balls
Point point1 = new Point();
point1.x = 50;
point1.y = 20;
Point point2 = new Point();
point2.x = 100;
point2.y = 20;
Point point3 = new Point();
point3.x = 150;
point3.y = 20;

// declare each ball with the ColorBall class
colorballs[0] = new ColorBall(context,R.drawable.bol_groen, point1);
colorballs[1] = new ColorBall(context,R.drawable.bol_rood, point2);
colorballs[2] = new ColorBall(context,R.drawable.bol_blauw, point3);

}

// the method that draws the balls
@Override protected void onDraw(Canvas canvas) {
//canvas.drawColor(0xFFCCCCCC); //if you want another background color

//draw the balls on the canvas
for (ColorBall ball : colorballs) {
canvas.drawBitmap(ball.getBitmap(), ball.getX(), ball.getY(), null);
}

}

// events when touching the screen
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();

int X = (int)event.getX();
int Y = (int)event.getY();

switch (eventaction ) {

case MotionEvent.ACTION_DOWN: // touch down so check if the finger is on a ball
balID = 0;
for (ColorBall ball : colorballs) {
// check if inside the bounds of the ball (circle)
// get the center for the ball
int centerX = ball.getX() + 25;
int centerY = ball.getY() + 25;

// calculate the radius from the touch to the center of the ball
double radCircle = Math.sqrt( (double) (((centerX-X)*(centerX-X)) + (centerY-Y)*(centerY-Y)));

// if the radius is smaller then 23 (radius of a ball is 22), then it must be on the ball
if (radCircle < 23){
balID = ball.getID();
break;
}

// check all the bounds of the ball (square)
//if (X > ball.getX() && X < ball.getX()+50 && Y > ball.getY() && Y < ball.getY()+50){
// balID = ball.getID();
// break;
//}
}

break;

case MotionEvent.ACTION_MOVE: // touch drag with the ball
// move the balls the same as the finger
if (balID > 0) {
colorballs[balID-1].setX(X-25);
colorballs[balID-1].setY(Y-25);
}

break;

case MotionEvent.ACTION_UP:
// touch drop – just do things here after dropping

break;
}
// redraw the canvas
invalidate();
return true;

}
}

Download File from url in Android

private void downloadFile(String url) {

try {

String imageFile = url.substring(url.lastIndexOf(“/”) + 1, url.length());

      URL u = new URL(url);

      URLConnection conn = u.openConnection();

      int contentLength = conn.getContentLength();

      DataInputStream stream = new DataInputStream(u.openStream());

        byte[] buffer = new byte[contentLength];

        stream.readFully(buffer);

        stream.close();

        DataOutputStream fos = new DataOutputStream(new FileOutputStream(Outputfilepath + “/”+imageFile));

        fos.write(buffer);

        fos.flush();

        fos.close();

  } catch(FileNotFoundException e) {

      return; // swallow a 404

  } catch (IOException e) {

      return; // swallow a 404

  }

}

Get Device Details Android

String details = “VERSION.RELEASE : “+Build.VERSION.RELEASE
+”\nVERSION.INCREMENTAL : “+Build.VERSION.INCREMENTAL
+”\nVERSION.SDK.NUMBER : “+Build.VERSION.SDK_INT
+”\nBOARD : “+Build.BOARD
+”\nBOOTLOADER : “+Build.BOOTLOADER
+”\nBRAND : “+Build.BRAND
+”\nCPU_ABI : “+Build.CPU_ABI
+”\nCPU_ABI2 : “+Build.CPU_ABI2
+”\nDISPLAY : “+Build.DISPLAY
+”\nFINGERPRINT : “+Build.FINGERPRINT
+”\nHARDWARE : “+Build.HARDWARE
+”\nHOST : “+Build.HOST
+”\nID : “+Build.ID
+”\nMANUFACTURER : “+Build.MANUFACTURER
+”\nMODEL : “+Build.MODEL
+”\nPRODUCT : “+Build.PRODUCT
+”\nSERIAL : “+Build.SERIAL
+”\nTAGS : “+Build.TAGS
+”\nTIME : “+Build.TIME
+”\nTYPE : “+Build.TYPE
+”\nUNKNOWN : “+Build.UNKNOWN
+”\nUSER : “+Build.USER;
 
Log.e(“Device Details”,details);