Sunday, 22 April 2018

Admob AdListener Example


0

Tuesday, 27 March 2018

Fragment Communication [Fragment to Activity]


0

Thursday, 28 December 2017

Shared Preferences in Android. Save Data


<?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.arham.csdevbin.downloadimagefrominternet.SharedPreferencesDemo">
    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="103dp"
        android:layout_marginStart="103dp"
        android:layout_marginTop="136dp"
        android:text="CheckBox" />
</RelativeLayout>



package com.arham.csdevbin.downloadimagefrominternet;

  import android.content.SharedPreferences;
  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.widget.CheckBox;
  import android.widget.CompoundButton;
  import android.widget.Toast;

  public class SharedPreferencesDemo extends AppCompatActivity implements
 CompoundButton.OnCheckedChangeListener {
    CheckBox checkBox;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences);
        checkBox = findViewById(R.id.checkBox);
        checkBox.setOnCheckedChangeListener(this);
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            checkBox.setText("The CheckBox is Checked");
        } else {
            checkBox.setText("The CheckBox is not Checked");
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();
        SharedPreferences sharedPreferences = getPreferences(0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("CHECK_BOX_VALUE", checkBox.getText().toString());
        editor.putBoolean("CH", checkBox.isChecked());
        editor.commit();
    }
    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
        SharedPreferences sharedPreferences = getPreferences(0);
        boolean checkBoxValue = sharedPreferences.getBoolean("CH", false);
        String chBoxString = sharedPreferences.getString("CHECK_BOX_VALUE", "This is my CheckBox");
        checkBox.setChecked(checkBoxValue);
        checkBox.setText(chBoxString);
    }
}


0

Downloading Image From Internet in Android


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"
   
android:orientation="vertical"
   
tools:context="com.arham.csdevbin.downloadimagefrominternet.MainActivity">

    <
ImageView
       
android:id="@+id/imageView"
       
android:layout_width="300dp"
       
android:layout_height="400dp"
       
android:layout_gravity="center_horizontal"
       
android:layout_marginTop="30dp"
       
app:layout_constraintLeft_toLeftOf="parent"
       
app:layout_constraintRight_toRightOf="parent"
       
app:srcCompat="@mipmap/ic_launcher"
       
tools:layout_editor_absoluteY="45dp" />

    <
Button
       
android:id="@+id/button"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:layout_gravity="center_horizontal"
       
android:layout_marginTop="20dp"
       
android:text="Download Image"
       
app:layout_constraintLeft_toLeftOf="parent"
       
app:layout_constraintRight_toRightOf="parent"
       
tools:layout_editor_absoluteY="152dp" />
</
LinearLayout>


MainActivity.java
package com.arham.csdevbin.downloadimagefrominternet;

  import android.app.ProgressDialog;
  import android.content.Context;
  import android.graphics.Bitmap;
  import android.graphics.BitmapFactory;
  import android.os.AsyncTask;
  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Button;
  import android.widget.ImageView;
  import java.io.InputStream;
  import java.net.URL;

  public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ImageView imageView;
    Button btnD;

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

        imageView = findViewById(R.id.imageView);
        btnD = findViewById(R.id.button);
        btnD.setOnClickListener(MainActivity.this);
    }
    @Override
    public void onClick(View v) {
        DownloadImageTask downloadImageTask = new DownloadImageTask(MainActivity.this);
        downloadImageTask.execute("http://www.gettyimages.ca/gi-resources" +
                "/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg");
    }  

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

        ProgressDialog progressDialog;
        Context context;

        public DownloadImageTask(Context context) {
            this.context = context;
            progressDialog = new ProgressDialog(context);
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog.setMessage("Downloading Image... Please Wait");
            progressDialog.show();
        }
        @Override
        protected Bitmap doInBackground(String... params) {
            String stringUrl = params[0];
            Bitmap bitmap = null;

            try {
                URL url = new URL(stringUrl);
                InputStream inputStream = url.openStream();
                bitmap = BitmapFactory.decodeStream(inputStream);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);

            imageView.setImageBitmap(bitmap);
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        }
    }
}



0

Wednesday, 20 December 2017

AsyncTask in Android Tutorial

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as ExecutorThreadPoolExecutor and FutureTask.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute
LoadAsycTask.java
public class LoadAsycTask extends AsyncTask<Void, Void, Void> {
    ProgressDialog
progressDialog;

   
private final Context mContext;

   
public LoadAsycTask(Context mContext) {
       
this.mContext = mContext;
    }


   
@Override
   
protected void onPreExecute() {
       
super.onPreExecute();
       
progressDialog = ProgressDialog.show(this.mContext, "Loading", "please wait....");
    }

   
@Override
   
protected Void doInBackground(Void... params) {
       
try {
            Thread.sleep(
3000);
        }
catch (InterruptedException e) {
            e.printStackTrace();
        }
       
return null;
    }

   
@Override
   
protected void onPostExecute(Void aVoid) {
       
super.onPostExecute(aVoid);
       
progressDialog.dismiss();
      
// Toast.makeText(mContext, "result pubslished", Toast.LENGTH_SHORT).show();
   
}
}

onCreate Methode:


............

LoadAsycTask loadAsycTask = new LoadAsycTask(MainActivity.this);

loadAsycTask.execute();








0

Wednesday, 6 December 2017

How to add an Android Studio project to GitHub ?

·         Sign up and create a GitHub account in www.github.com.
·         Download git from https://git-scm.com/downloads and install it in your system.
·         Open the project in android studio and go to File -> Settings -> Version Control -> Git.
·         Click on test button to test "path to Git executables". If successful message is shown everything is ok, else navigate to git.exe from where you installed git and test again.
·         Go to File -> Settings -> Version Control -> GitHub. Enter your email and password used to create GitHub account and click on OK button.
·         Then go to VCS -> Import into Version Control -> Share Project on GitHub. Enter Repository name, Description and click Share button.
·         In the next window check all files inorder to add files for initial commit and click OK.
·         Now the project will be uploaded to the GitHub repository and when uploading is finished we will get a message in android studio showing "Successfully shared project on GitHub". Click on the link provided in that message to go to GitHub repository.

source : https://stackoverflow.com/questions/37093723/how-to-add-an-android-studio-project-to-github



Commit after  making a change 

Go to VCS -> Git -> Commit file . Then type a commit message and click on commit button.

 

0

Sunday, 3 December 2017

JSON parsing and Displaying in ListView

1. manisfests.xml


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

2.mainActivity.xml

<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"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="invisible" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true" />

</RelativeLayout>

3.activity_detail

<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"
    tools:context=".detail">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />
</RelativeLayout>

4.MainActivity.java

package com.arham.csdevbin.apidemo;

  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.support.v7.app.AppCompatActivity;
  import android.view.View;
  import android.widget.AdapterView;
  import android.widget.ArrayAdapter;
  import android.widget.ListView;
  import android.widget.ProgressBar;
  import java.util.ArrayList;
  import java.util.List;

  public class MainActivity extends AppCompatActivity {
 
    private ProgressBar pb;
    private ListView lv;
    private List<String> contactList;

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

        contactList = new ArrayList<>();
        pb = (ProgressBar) findViewById(R.id.progressBar);
        lv = (ListView) findViewById(R.id.listView);

        /*fetch data from the web*/
        Fetcher fetcher = new Fetcher();
        fetcher.execute("https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=
b63009d5896f4fe19251a328a69c1835");

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name = (String) lv.getItemAtPosition(position);
                Intent intent = new Intent(MainActivity.this, detail.class);
                intent.putExtra("name", name);
                startActivity(intent);
            }
        });
    }

    public void ContactAdapter(String json) {
        contactList = JsonParser.Parse(json);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
              android.R.layout.simple_list_item_1, contactList); 
       lv.setAdapter(adapter);
    }

    //AsyncTask
    private class Fetcher extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            pb.setVisibility(View.VISIBLE);
        }

        @Override 
       protected String doInBackground(String... params) {
            String data = HttpManger.getData(params[0]);
            return data;

        }
        @Override
        protected void onPostExecute(String s) {
            ContactAdapter(s);
            pb.setVisibility(View.INVISIBLE);
        }
    }
}

 5.JsonParser.java

package com.arham.csdevbin.apidemo;

  import android.util.Log;
  import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;
  import java.util.ArrayList;
  import java.util.List;

  public class JsonParser {
    public static List<String> Parse(String json) {
        try {
            JSONObject response = new JSONObject(json);
            JSONArray articles = response.optJSONArray("articles");
            List<String> contactList = new ArrayList<>();
 
            for (int i = 0; i < articles.length(); i++) {
                JSONObject article = articles.optJSONObject(i);
                contactList.add(article.getString("title"));
            }
            return contactList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
}

6.HttpManger.java

package com.arham.csdevbin.apidemo;
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.net.HttpURLConnection;
  import java.net.URL;

  public class HttpManger {

    public static String getData(String stringUrl) {
        BufferedReader reader = null;

        try {
            URL url = new URL(stringUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            InputStreamReader is = new InputStreamReader(connection.getInputStream());

            reader = new BufferedReader(is);
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;

        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

7.detail.java

package com.arham.csdevbin.apidemo;
  import android.os.Bundle;
  import android.support.v7.app.AppCompatActivity;
  import android.widget.TextView;

  public class detail extends AppCompatActivity {

    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        tv = (TextView)findViewById(R.id.textView);

        //store the text in variable
        String name = getIntent().getExtras().getString("name");
        //display text
        tv.setText(name);
    }
}



0