Change background Edittext in Click Event in android

Screenshot





Create file in Drawable folder


Editbg.xml

<?xml version="1.0" encoding="utf-8"?><selector xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"        android:drawable="@color/colorAccent"/> <!-- pressed -->    <item android:state_focused="true"        android:drawable="@color/colorWhite"/> <!-- focused -->    <item android:drawable="@color/colorAccent" /> <!-- default -->


</selector>



And Use in Your layout xml file 


android:background="@drawable/edit_background"

Android Relative layout example

Android Relative layout example
relativelayout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="30dp">

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:gravity="center"
        android:text="1"
        android:textSize="20dp"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/button3"
        android:layout_toStartOf="@+id/button3"
        android:background="@drawable/color"
        android:textColor="#fff"/>
    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="2"
        android:textSize="20dp"
        android:id="@+id/button3"
        android:background="@color/colorAccent"
        android:textColor="#fff"/>
    <Button
        android:id="@+id/b3"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="3"
        android:textSize="20dp"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/button3"
        android:layout_toEndOf="@+id/button3"
        android:background="@drawable/color"
        android:textColor="#fff"/>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="57dp"
        android:id="@+id/linearLayout"
        android:layout_below="@+id/button"
        android:layout_alignLeft="@+id/button"
        android:layout_alignStart="@+id/button"
        android:layout_alignRight="@+id/b3"
        android:layout_alignEnd="@+id/b3">

        <Button
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:text="4"
            android:textSize="20dp"
            android:background="@color/colorAccent"
            android:textColor="#fff"/>
        <Button
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_centerHorizontal="true"
            android:gravity="center"
            android:text="5"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"
            />

        <Button
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:text="7"
            android:background="@color/colorAccent"
            android:textColor="#fff"
            android:textSize="20dp"/>

    </LinearLayout>

    <Button
        android:id="@+id/button4"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:gravity="center"
        android:text="7"
        android:textSize="20dp"
        android:layout_below="@+id/linearLayout"
        android:layout_alignLeft="@+id/linearLayout"
        android:layout_alignStart="@+id/linearLayout"
        android:background="@drawable/color"
        android:textColor="#fff"/>

    <Button
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_below="@+id/linearLayout"
        android:layout_toRightOf="@+id/button4"
        android:layout_toEndOf="@+id/button4"
        android:text="8"
        android:textSize="20dp"
        android:background="@color/colorAccent"
        android:textColor="#fff"/>
    <Button
        android:id="@+id/button5"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="100dp"
        android:layout_marginStart="100dp"
        android:layout_toEndOf="@+id/button4"
        android:layout_toRightOf="@+id/button4"
        android:text="9"
        android:textSize="20dp"
        android:layout_below="@+id/linearLayout"
        android:background="@drawable/color"
        android:textColor="#fff"/>

    <Button
        android:layout_marginTop="20mm"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_toRightOf="@+id/button4"
        android:layout_marginBottom="13dp"
        android:textSize="20dp"
        android:text="0"
        android:background="@drawable/color"
        android:textColor="#fff"/>
</RelativeLayout>

Android linear layout example

Android linear layout example
linear.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="4"
    tools:context="com.example.pc.myapplication.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">

        <Button
            android:id="@+id/b1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="1"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>

        <Button
            android:id="@+id/b2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="2"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>

        <Button
            android:id="@+id/b3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="3"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:textSize="20dp">

        <Button
            android:id="@+id/b4"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="4"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>

        <Button
            android:id="@+id/b5"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="5"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>

        <Button
            android:id="@+id/b6"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="6"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">

        <Button
            android:id="@+id/b7"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="7"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>

        <Button
            android:id="@+id/b8"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="8"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>

        <Button
            android:id="@+id/b9"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="9"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:paddingLeft="130dp"
        android:paddingRight="130dp">

        <Button
            android:id="@+id/b0"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="0"
            android:textSize="20dp"
            android:background="@drawable/color"
            android:textColor="#fff"/>
    </LinearLayout>

</LinearLayout>

Android Activity example

Android Activity example
Android Activity

  • onCreate()
  • onStart()
  • onResume()
  • onPause()
  • onStop()
  • onDestroy
whenever activity call in android into one screen to another screen and activity of screen A and Screen B it display Toast message.

Here we layout click event 


activity_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:id="@+id/lay1"
    tools:context="com.example.anshu.intent_example.ActivityA">

</android.support.constraint.ConstraintLayout>


and another 
activity_b.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:id="@+id/lay2"
    tools:context="com.example.anshu.intent_example.ActivityB">

</android.support.constraint.ConstraintLayout>



ActivityA.java

package com.example.anshu.intent_example;

import android.content.Context;
import android.content.Intent;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ActivityA extends AppCompatActivity {

    ConstraintLayout lay1;

    public Context context;

   //utils ut = new utils();
   //ut.



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity);
        lay1 = (ConstraintLayout) findViewById(R.id.lay1);

        lay1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),ActivityB.class);
                startActivity(i);
            }
        });

        Toast.makeText(this,"A >> is Created",Toast.LENGTH_SHORT).show();
        //utils utl = new utils();

        //utl.toast("A is Created",);
        //utl.toast("A create ",);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //utils utl = new utils();
        //utl.toast("A create ",this);
        Toast.makeText(this,"A >> is started",Toast.LENGTH_SHORT).show();
        //this.context = c;//Context context;

    }

    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this,"A >> is resume",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this,"A >> is pause",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Toast.makeText(this,"A >> is stop",Toast.LENGTH_SHORT).show();
    }



}



ActivityB.java

package com.example.anshu.intent_example;

import android.content.Context;
import android.content.Intent;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class ActivityB extends AppCompatActivity {

    ConstraintLayout lay2;
    public Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);

        lay2 = (ConstraintLayout) findViewById(R.id.lay2);

        lay2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),ActivityA.class);
                startActivity(i);


            }
        });
        Toast.makeText(this,"B >> is Created",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Toast.makeText(this,"B >> is Started",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this,"B >> is Resume",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this,"B >> is Pause",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Toast.makeText(this,"B >> is Stop",Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"B >> is Destroy",Toast.LENGTH_SHORT).show();
    }
}


utils.java

package com.example.anshu.intent_example;

import android.content.Context;
import android.widget.Toast;

public class utils {
   public void toast(String stringmsg, Context mcontext)
   {
       Toast.makeText(mcontext,stringmsg,Toast.LENGTH_SHORT).show();
   }
}

Android Broadcast example

Android Broadcast example
Simple Android broadcast example 



Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="com.example.anshu.broadcast.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Example of Broadcast"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30dp" />


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="Broadcast Intent"
        android:onClick="broadcastIntent"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true" />

</RelativeLayout>



MainActivity.java
package com.example.anshu.broadcast;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

    Button b1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    b1 = (Button) findViewById(R.id.button2);

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                Intent intent = new Intent();
                intent.setAction("com.tutorialspoint.CUSTOM_INTENT");
                sendBroadcast(intent);
           
        }
    });

    }


}


MyReceiver.java

package com.example.anshu.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by Anshu on 12/8/2017.
 */

public class MyReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"Intent Detected.",Toast.LENGTH_LONG).show();
    }
}

Android JSON parsing OkHttp and Display in Listview Picasso Library

Screenshots :





URL :- https://api.androidhive.info/json/movies.json


Get data two Image and title from URL 


Step 1 : Create a new project in Android studio IDE File ⇒ New ⇒ Android Application Project and fill all the required details.


Step 2 : In xml file place List view and image view code below.


Step 3 : Add Internet Permission in your project manifest file .
                
    <uses-permission android:name="android.permission.INTERNET" />



 Step 4 : Create XML file named activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.webbleu8.ok.MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>


-------------------------------------------------------------------------------------------------------------


STEP 5 :  Create Xml file named custom_item.xml 


custom_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/image"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:scaleType="fitXY" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:textColor="#000000" />

</LinearLayout>






------------------------------------------------------------------------------------------------
STEP 6 :  Create Main_activity.java and declare  necessary variables for the list view. 


Main_Activity.java

package com.example.webbleu8.ok;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayList<String> genre = new ArrayList<>();
    ArrayList<model> list;
    ListView listView;
    ProgressDialog pDialog;
    AppAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter = new AppAdapter();
        pDialog = new ProgressDialog(MainActivity.this);
        list = new ArrayList<>();
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);

        new GetContacts().execute();
    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {
        String url = "https://api.androidhive.info/json/movies.json";
        String title, image, rating, year;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            if (jsonStr != null) {
                try {
                    // Getting JSON Array node
                    JSONArray contacts = new JSONArray(jsonStr);

                    // looping through All Contacts
                    genre.clear();
                    list.clear();
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        title = c.getString("title");
                        image = c.getString("image");
                        rating = c.getString("rating");
                        year = c.getString("releaseYear");

                        JSONArray jsonArray = c.getJSONArray("genre");

                       /* for (int j = 0; j < jsonArray.length(); j++) {
genre.add(jsonArray.getString(j));

                        }*/

                        /*System.out.println(" genre  array   " + genre);*/
                        model model = new model();
                        model.setTitle(title);
                        model.setImage(image);
                        list.add(model);
                        System.out.println(" Title     " + title);
                        System.out.println(" rating        " + rating);
                        System.out.println(" release year         " + year);
                        System.out.println("Image            " + image);
                    }

                    Log.d("ARRAY>> ", "" + list.size());

                } catch (final JSONException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }

            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show();
                    }
                });
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            adapter.notifyDataSetChanged();
            System.out.println("Image_path==================" + image);
        }

    }

    private class AppAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public model getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(getApplicationContext(), R.layout.custom_item, null);
                new ViewHolder(convertView);
            }
            final ViewHolder holder = (ViewHolder) convertView.getTag();

            final model model = getItem(position);
            holder.text.setText(model.getTitle());
            Picasso.with(getApplicationContext()).load(model.getImage()).into(holder.image);

            return convertView;
        }

        class ViewHolder {
            TextView text;
            ImageView image;

            ViewHolder(View view) {
                text = (TextView) view.findViewById(R.id.text);
                image = (ImageView) view.findViewById(R.id.image);

                view.setTag(this);
            }
        }

    }
}



STEP 7 : Create Model.java class for get perticular data (image, Title)

model.java



package com.example.webbleu8.ok;


public class model {

    String title, image;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}



Create HTTPURLConnection .java 


HTTPURLConnection.java




package com.example.webbleu8.ok;

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class HTTPURLConnection
{
    String response="";
    URL url;

    public String ServerData(String path, HashMap<String, String> params)
    {
        try
        {
            url = new URL(path);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(params));
            writer.flush();
            writer.close();

            os.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                    Log.d("output lines", line);
                }
            } else {
                response = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }

}


Create a class HttpHandler.java and fetch particular URL and fetch the response 


HttpHandler.java


package com.example.webbleu8.ok;


import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpHandler
{
    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is)
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null)
            {
                sb.append(line).append('\n');
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        } finally
        {
            try
            {
                is.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

Android webservice celcius to farenheit using KSOAP library

Android webservice celcius to farenheit using KSOAP library

Include the KSOAP2 jar file in to your project. Right click project ⇒ Properties ⇒ Java build path ⇒ Libraries Tab ⇒ Add External Jars ⇒ browse and add KSOAP2 Jar file.



activity_ksoap_test.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.anshu.ksoap.KsoapTestActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="data" />

    <EditText
        android:id="@+id/cel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/cel2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculate" />
</LinearLayout>


KsoapTestActivity.java


package com.example.anshu.ksoap;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class KsoapTestActivity extends AppCompatActivity {

    String TAG = "Response";
    Button bt;
    EditText celcius;
    String getCel;
    TextView text;
    SoapPrimitive resultString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ksoap_test);

        bt = (Button) findViewById(R.id.bt);
        celcius = (EditText) findViewById(R.id.cel);
        text = (TextView) findViewById(R.id.text);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCel = celcius.getText().toString();
                AsyncCallWS task = new AsyncCallWS();
                task.execute();
            }
        });
    }


    private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
        }


        @Override
        protected Void doInBackground(Void... params) {
            Log.i(TAG, "doInBackground");
            calculate();
            return null;
        }


        @Override
        protected void onPostExecute(Void result) {
            Log.i(TAG, "onPostExecute");
            text.setText(resultString.toString());
            //Toast.makeText(KsoapTestActivity.this, "Response is :" + resultString.toString(), Toast.LENGTH_LONG).show();


        }
    }

    private void calculate() {
        String SOAP_ACTION = "https://www.w3schools.com/xml/CelsiusToFahrenheit";
        String METHOD_NAME = "CelsiusToFahrenheit";
        String NAMESPACE = "https://www.w3schools.com/xml/";
        String URL = "https://www.w3schools.com/xml/tempconvert.asmx";


        try {
            SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
            Request.addProperty("Celsius", getCel);

            SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            soapEnvelope.dotNet = true;
            soapEnvelope.setOutputSoapObject(Request);

            HttpTransportSE transport = new HttpTransportSE(URL);

            transport.call(SOAP_ACTION, soapEnvelope);
            resultString = (SoapPrimitive) soapEnvelope.getResponse();

            Log.i(TAG, "Result Celsius: " + resultString);
        } catch (Exception ex) {
            Log.e(TAG, "Error: " + ex.getMessage());
        }
    }
}


WebserviceCall.java


package com.example.anshu.ksoap;


import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
/**
 * Created by Anshu on 21-Dec-17.
 */

class WebserviceCall {


    String namespace = " http://www.webserviceX.NET/";
    private String url = "http://www.webservicex.net/ConvertWeight.asmx";
    String SOAP_ACTION;
    SoapObject request = null, objMessages = null;
    SoapSerializationEnvelope envelope;
    AndroidHttpTransport androidHttpTransport;

    WebserviceCall() {
    }
    protected void SetEnvelope() {

        try {

            // Creating SOAP envelope
            envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            //You can comment that line if your web service is not .NET one.
            envelope.dotNet = true;

            envelope.setOutputSoapObject(request);
            androidHttpTransport = new AndroidHttpTransport(url);
            androidHttpTransport.debug = true;

        } catch (Exception e) {
            System.out.println("Soap Exception---->>>" + e.toString());
        }
    }



    public String getConvertedWeight(String MethodName, String weight, String fromUnit, String toUnit) {

        try {
            SOAP_ACTION = namespace + MethodName;

            //Adding values to request object
            request = new SoapObject(namespace, MethodName);

            //Adding Double value to request object
            PropertyInfo weightProp =new PropertyInfo();
            weightProp.setName("Weight");
            weightProp.setValue(weight);
            weightProp.setType(double.class);
            request.addProperty(weightProp);

            //Adding String value to request object
            request.addProperty("FromUnit", "" + fromUnit);
            request.addProperty("ToUnit", "" + toUnit);

            SetEnvelope();

            try {

                //SOAP calling webservice
                androidHttpTransport.call(SOAP_ACTION, envelope);

                //Got Webservice response
                String result = envelope.getResponse().toString();

                return result;

            } catch (Exception e) {
                // TODO: handle exception
                return e.toString();
            }
        } catch (Exception e) {
            // TODO: handle exception
            return e.toString();
        }


    }
}

splash screen and shared preference in android

Screenshots






Designing part of splash screen and shared preference in android 


splashfile.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/logo_id"
        android:layout_width="300dp"
        android:layout_height="700dp"
        android:layout_centerInParent="true"
        android:src="@drawable/aaa"/>



</RelativeLayout>






activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.anshu.sharedpreference.MainActivity">



    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/etName"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="75dp"
        android:hint="Enter Name" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/etPassword"
        android:layout_below="@+id/etName"
        android:layout_centerHorizontal="true"
        android:hint="Enter Password" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/btnLogin"
        android:layout_below="@+id/etPassword"
        android:layout_alignLeft="@+id/etPassword"
        android:layout_alignStart="@+id/etPassword" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register"
        android:id="@+id/btnRegister"
        android:layout_alignTop="@+id/btnLogin"
        android:layout_toRightOf="@+id/btnLogin"
        android:layout_toEndOf="@+id/btnLogin" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="18dp"
        android:textSize="30dp"
        android:text="Login" />

</RelativeLayout>





register.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">



    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/etNewName"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="58dp"
        android:hint="Enter Username" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/etNewPassword"
        android:layout_below="@+id/etNewName"
        android:layout_centerHorizontal="true"
        android:hint="Enter Password" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/etcompassword"
        android:layout_below="@+id/etNewPassword"
        android:layout_centerHorizontal="true"
        android:hint="Re Enter Password" />
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etNewEmail"
        android:layout_below="@+id/etcompassword"
        android:layout_alignLeft="@+id/etNewPassword"
        android:layout_alignStart="@+id/etNewPassword"
        android:layout_alignRight="@+id/etNewPassword"
        android:layout_alignEnd="@+id/etNewPassword"
        android:hint="Enter Name" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register"
        android:id="@+id/btnNewRegister"
        android:layout_below="@+id/etNewEmail"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnNewRegister"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/btnNewRegister"
        android:text="Sign up"
        android:textSize="30dp" />


</RelativeLayout>




display_info


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1">


    <TextView
        android:textSize="20sp"
        android:textStyle="bold"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:text="New Text"
        android:id="@+id/textViewName"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="121dp" />


    <TextView
        android:id="@+id/textViewName2"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:layout_alignLeft="@+id/textViewName"
        android:layout_alignStart="@+id/textViewName"
        android:layout_below="@+id/textViewName"
        android:layout_marginTop="25dp"
        android:text="New Text"
        android:textSize="20sp"
        android:textStyle="bold" />


    <Button
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:textSize="20dp"
        android:text="Logout"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:id="@+id/logout"/>

</RelativeLayout>


----------------------------------------------------------------------------------------------------------------------



Coding part of  splash screen and shared preference in android 


SplashActivity.java

package com.example.anshu.sharedpreference;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;

/**
 * Created by Anshu on 12/13/2017.
 */

public class SplashActivity extends Activity {

    SharedPreferences sharedpreferences;
    public static String str_login_test;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashfile);


        handler=new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {


        SharedPreferences preferences = getSharedPreferences("MYPREFS", MODE_PRIVATE);
        str_login_test = preferences.getString("Username","");


        final String userName = preferences.getString("Username", "");
        final String password1 = preferences.getString("Password", "");

        if (!userName.equalsIgnoreCase("") && !password1.equalsIgnoreCase("")) {
            startActivity(new Intent(SplashActivity.this, DisplayScreen.class));
            finish();

        }
        else {
            Intent SplashActivity = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(SplashActivity);
            finish();
        }



        /*

        final String userName = preferences.getString("Username", "");
        final String password1 = preferences.getString("Password", "");
*/

                /*Intent intent=new Intent(SplashActivity.this,MainActivity.class);
                startActivity(intent);*/
                //finish();
            }
        },3000);
    }
}





MainActivity

package com.example.anshu.sharedpreference;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText etName, etPassword;
    Button btnLogin, btnRegister;
    SharedPreferences sharedpreferences;
    String userName,password1,email;

    public static final String MyPREFERENCES = "MyPrefs";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        etName = (EditText) findViewById(R.id.etName);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                return false;
            }
        });


        btnLogin = (Button) findViewById(R.id.btnLogin);
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        btnRegister = (Button) findViewById(R.id.btnRegister);

        SharedPreferences preferences = getSharedPreferences("MYPREFS", MODE_PRIVATE);

//                String userDetails = preferences.getString(user + password + "data","No information on that user.");
//                SharedPreferences.Editor editor = preferences.edit();
//                editor.putString("display",userDetails);
//                editor.commit();


         userName = preferences.getString("Username", "");
         password1 = preferences.getString("Password", "");
         email = preferences.getString("email", "");



        /*if (!userName.equalsIgnoreCase("") && !password1.equalsIgnoreCase("")){
            startActivity(new Intent(MainActivity.this,DisplayScreen.class));
            finish();
        }*/


        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String user = etName.getText().toString();
                String password = etPassword.getText().toString();


                if (etName.getText().toString().trim().length() == 0) {
                    etName.setError("User Name is not entered");
                    etName.requestFocus();
                } else if (etPassword.getText().toString().trim().length() == 0) {
                    etPassword.setError("Password is not entered");
                    etPassword.requestFocus();
                } else if (!userName.equals(user)) {
                    Toast.makeText(MainActivity.this, "UserName does not match", Toast.LENGTH_SHORT).show();
                } else if (!password1.equals(password)) {
                    Toast.makeText(MainActivity.this, "Password does not match", Toast.LENGTH_SHORT).show();
                } else {
                    startActivity(new Intent(MainActivity.this, DisplayScreen.class));
                }
                /*else {
                    Intent intent = new Intent(getApplicationContext(),DisplayScreen.class);
                    startActivity(intent);
                }*/




                /*Intent displayScreen = new Intent(MainActivity.this, DisplayScreen.class);
                startActivity(displayScreen);*/
                /*loginCheck();*/

            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent registerScreen = new Intent(MainActivity.this, Register.class);
                startActivity(registerScreen);
            }
        });


    }

    //Important

     /*void loginCheck() {
        if (etName.getText().toString().equals("Anshu") && etPassword.getText().toString().equals("Anshu1"))
        {
            SharedPreferences.Editor e=sp.edit();
            e.putString("etName","Anshu");
            e.putString("etPassword","Anshu1");
            e.commit();

            Toast.makeText(MainActivity.this,"Login Sucessful",Toast.LENGTH_SHORT).show();
            startActivity(new Intent(MainActivity.this,DisplayScreen.class));
            finish();
        }
        else {
            Toast.makeText(MainActivity.this,"Incorrect Login Details",Toast.LENGTH_SHORT).show();
       */

}



Register.java


package com.example.anshu.sharedpreference;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by Anshu on 12/13/2017.
 */

public class Register extends AppCompatActivity {

    EditText username, password, reenterpass, email;
    Button btnRegister;
    SharedPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        init();
    }


    private void init() {
        username = (EditText) findViewById(R.id.etNewName);
        reenterpass = (EditText) findViewById(R.id.etcompassword);
        password = (EditText) findViewById(R.id.etNewPassword);
        email = (EditText) findViewById(R.id.etNewEmail);
        btnRegister = (Button) findViewById(R.id.btnNewRegister);
        preferences = getSharedPreferences("MYPREFS", MODE_PRIVATE);
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View v) {
                validation();
            }
        });
    }

    private void validation() {
        if (username.getText().toString().length() == 0) {
            username.setError("User name is Required");
        } else if (password.getText().toString().length() == 0) {
            password.setError("Password Required");
        } else if (reenterpass.getText().toString().length() == 0) {
            reenterpass.setError("Password Required");
        } else if (email.getText().toString().length() == 0) {
            email.setError("Email is Requied");
        } else if (!password.getText().toString().trim().equals(reenterpass.getText().toString())) {
            Toast.makeText(Register.this, "Password Not Match", Toast.LENGTH_SHORT).show();
        } else {
            //After Register it will be redirect to login page
            String newUser = username.getText().toString();
            String newPassword = password.getText().toString();
            String newEmail = email.getText().toString();

            SharedPreferences.Editor editor = preferences.edit();

            editor.putString("Username", newUser);
            editor.commit();
            editor.putString("Password", newPassword);
            editor.commit();
            editor.putString("email", newEmail);
            editor.commit();
            Intent MainActivity = new Intent(Register.this, MainActivity.class);
            startActivity(MainActivity);
        }
    }
}



DisplayScreen.java


package com.example.anshu.sharedpreference;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.jar.Attributes;

/**
 * Created by Anshu on 12/13/2017.
 */

public class DisplayScreen extends Activity implements View.OnClickListener {


    String name1,email;
    TextView UserName,name;
    SharedPreferences preferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display_info);

        Button logout = (Button) findViewById(R.id.logout);
        logout.setOnClickListener(this);

        SharedPreferences preferences = getSharedPreferences("MYPREFS", MODE_PRIVATE);
        String display = preferences.getString("Username", "");
        String display1 = preferences.getString("email", "");
   /*     String display1 = preferences.getString("email", "");
*/
        /*StringBuilder builder = new StringBuilder();
        builder.append("UserName : "+UserName);*/

        TextView displayInfo = (TextView) findViewById(R.id.textViewName);
        displayInfo.setText(display);

        TextView Displayinfo1 = (TextView) findViewById(R.id.textViewName2);
        Displayinfo1.setText(display1);
        /*TextView displayInfo1 = (TextView) findViewById(R.id.etNewEmail);
        displayInfo1.setText(display1);*/



    }

    @Override
    public void onClick(View view) {
        SharedPreferences preferences = getSharedPreferences("MYPREFS", MODE_PRIVATE);
                    /*preferences.edit().clear().commit();*/
        SharedPreferences.Editor editor = preferences.edit();
        Toast.makeText(DisplayScreen.this, "You Have Sucessfullylogout", Toast.LENGTH_SHORT).show();
        editor.clear();
        //editor.apply();
        editor.commit();
                    /*editor.commit();*/
        Intent DisplayScreen = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(DisplayScreen);
    }
}