Android webservices Retrive Data

Android\Manifest.xml

<?xml version=“1.0” encoding=“utf-8”?>

<manifest xmlns:android=“http://schemas.android.com/apk/res/android”

  package=“com.gantasoft.recylerlist”>

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

  <application

      android:allowBackup=“true”

      android:icon=“@mipmap/ic_launcher”

      android:label=“@string/app_name”

      android:roundIcon=“@mipmap/ic_launcher_round”

      android:supportsRtl=“true”

      android:theme=“@style/AppTheme”>

      <activity android:name=“.MainActivity”>

          <intent-filter>

              <action android:name=“android.intent.action.MAIN” />


              <category android:name=“android.intent.category.LAUNCHER” />

          </intent-filter>

      </activity>

  </application>


</manifest>

java\com.gantasoft.recylerlist\MainActivity.java

 

package com.gantasoft.recylerlist;


import android.content.Context;

import android.content.SharedPreferences;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.support.v7.widget.LinearLayoutManager;

import android.support.v7.widget.RecyclerView;

import android.widget.TextView;


public class MainActivity extends AppCompatActivity {


  @Override

  protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);

      RecyclerView recyclerView=findViewById(R.id.recyler);



      recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,true));

      RecyclerView.LayoutManager pmLayoutManager =

              new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);

      recyclerView.setLayoutManager(pmLayoutManager);




      RegisterHelper registerHelper=new RegisterHelper(MainActivity.this,“http://gantasoft.com/Webservices/users_get.php”,recyclerView);

      registerHelper.execute();


  }

}

java\com.gantasoft.recylerlist\MyrecyclerRegisterExamp.java

 


import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.support.v7.widget.RecyclerView;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ImageView;

import android.widget.TextView;


import java.util.ArrayList;

import java.util.List;





public class MyrecyclerRegisterExamp extends RecyclerView

      .Adapter<MyrecyclerRegisterExamp

      .DataObjectHolder> {



  private static String LOG_TAG = “MyRecyclerViewAdapter”;

  private ArrayList<UserOBJ> mDataset;

  private MainActivity context;

  private static MyClickListener myClickListener;

  TextView keyName;

  String groupId, userId, firstName, lastName;


  private List< UserOBJ> itemList;



  String p_id,c_comment,id,btnName;

  //private DBManager dbManager;

  private static final int REQUEST_PHONE_CALL = 1;


  public MyrecyclerRegisterExamp(ArrayList< UserOBJ> myDataset, MainActivity context) {

      mDataset = myDataset;

      this.context = context;

  }




  public class DataObjectHolder extends RecyclerView.ViewHolder

  {


      TextView userName,userEmail;



      public DataObjectHolder(final View i) {

          super(i);

          userName=i.findViewById(R.id.text);

          userEmail=i.findViewById(R.id.text2);



      }



  }


  @Override

  public DataObjectHolder onCreateViewHolder(ViewGroup parent,

                                             int viewType) {

      View view = LayoutInflater.from(parent.getContext())

              .inflate(R.layout.recycler, parent, false);


      DataObjectHolder dataObjectHolder = new DataObjectHolder(view);

      return dataObjectHolder;

  }



  @Override

  public void onBindViewHolder(DataObjectHolder h, int position) {

      h.userName.setText(mDataset.get(position).getUser_name());

      h.userEmail.setText(mDataset.get(position).getUser_email());



  }


  @Override

  public int getItemCount() {

      return mDataset.size();

  }


  public interface MyClickListener {

      public void onItemClick(int position, View v);

  }




}

 

java\com.gantasoft.recylerlist\RegisterHelper.java

package com.gantasoft.recylerlist;


import android.app.ProgressDialog;

import android.os.AsyncTask;

import android.support.v7.widget.RecyclerView;


import com.google.gson.Gson;

import com.google.gson.reflect.TypeToken;


import java.lang.reflect.Type;

import java.net.URL;

import java.util.ArrayList;

import java.util.List;




/**

* Created by welcome on 6/30/2017.

*/


public class RegisterHelper extends AsyncTask<String, Void, String> {

  /*private CatagoryList mcontext;

  private ProgressDialog progress;

  String surl;

  RecyclerView rvGroups;


  String companyId;*/

  private MainActivity mainActivity;

  RecyclerView recyclerView;

  String surl;

  private ProgressDialog progress;

  public RegisterHelper(MainActivity mainActivity, String surl, RecyclerView recyclerView) {

      this.mainActivity = mainActivity;

      this.surl=surl;

      this.recyclerView=recyclerView;

  }

  @Override

  protected void onPreExecute() {

      super.onPreExecute();

      progress = new ProgressDialog(mainActivity);

      progress.setMessage(“Loading…”);

      progress.show();

  }


  protected String doInBackground(String… urls) {

      URL url = null;

      try {

          System.out.println(“Connection to url ……………..” + surl);

          url = new URL(surl);

      } catch (Exception e) {

          e.printStackTrace();

      }

      return RestServices.GET(url);

  }


  protected void onPostExecute(String result) {

      System.out.println(“Get Service Result is “+result);

      progress.dismiss();

      if (result!=null && result.trim().length()>0) {

          Gson gson = new Gson();

          Type type = new TypeToken<List<UserDTO>>() { }.getType();

          List<UserDTO> fromJson = gson.fromJson(result, type);

          ArrayList<UserOBJ> results = new ArrayList<UserOBJ>();

           for (UserDTO requests : fromJson) {


               UserOBJ obj = new UserOBJ(requests.getUser_id(),requests.getUser_name(),requests.getUser_email());

              results.add(obj);

         }

          if (!results.isEmpty()) {


              MyrecyclerRegisterExamp mAdapter = new MyrecyclerRegisterExamp(results, mainActivity);

              recyclerView.setAdapter(mAdapter);

              mAdapter.notifyDataSetChanged();

          }else{

              //noData.setVisibility(View.VISIBLE);

          }

      }

  }


}

java\com.gantasoft.recylerlist\RestServices.java

package com.gantasoft.recylerlist;


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.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;


public class RestServices {

  public static String POST(URL url, String json){

      InputStream inputStream = null;

      String result = “”;

      HttpURLConnection conn = null;

      try {


          Log.e(“URL”, “> ” + url);

          conn = (HttpURLConnection) url.openConnection();

          conn.setDoOutput(true);

          conn.setUseCaches(false);

          conn.setFixedLengthStreamingMode(json.getBytes().length);

          conn.setRequestMethod(“POST”);

          conn.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);

          conn.setRequestProperty(“X-Requested-With”, “XMLHttpRequest”);

          // post the request

          OutputStream out = conn.getOutputStream();

          out.write(json.getBytes());

          out.close();


          // handle the response

          inputStream = conn.getInputStream();

          if(inputStream != null)

              result = convertInputStreamToString(inputStream);

          else

              result = “Did not work!”;


      }

      catch (Exception e) {

          Log.d(“InputStream”, e.getLocalizedMessage());

      }

      return result;

  }

  public static String GET(URL url){

      InputStream inputStream = null;

      String result = “”;

      HttpURLConnection conn = null;

      try {


          Log.e(“URL”, “> ” + url);

          conn = (HttpURLConnection) url.openConnection();

          inputStream = new BufferedInputStream(conn.getInputStream());

          if(inputStream != null)

              result = convertInputStreamToString(inputStream);

          else

              result = “Did not work!”;


      }

      catch (Exception e) {

          Log.d(“InputStream”, e.getLocalizedMessage());

      }

      return result;

  }

  public static String PUT(URL url, String json){

      InputStream inputStream = null;

      String result = “”;

      HttpURLConnection conn = null;

      try {


          Log.e(“URL”, “> ” + url);

          conn = (HttpURLConnection) url.openConnection();

          conn.setDoOutput(true);

          conn.setUseCaches(false);

          conn.setFixedLengthStreamingMode(json.getBytes().length);

          conn.setRequestMethod(“PUT”);

          conn.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);

          conn.setRequestProperty(“X-Requested-With”, “XMLHttpRequest”);

          // post the request

          OutputStream out = conn.getOutputStream();

          out.write(json.getBytes());

          out.close();


          // handle the response

          inputStream = conn.getInputStream();

          if(inputStream != null)

              result = convertInputStreamToString(inputStream);

          else

              result = “Did not work!”;


      }

      catch (Exception e) {

          Log.d(“InputStream”, e.getLocalizedMessage());

      }

      return result;

  }

  public static String DELETE(URL url){

      InputStream inputStream = null;

      String result = “”;

      HttpURLConnection conn = null;

      try {


          Log.e(“URL”, “> ” + url);

          conn = (HttpURLConnection) url.openConnection();

          conn.setRequestMethod(“DELETE”);

          if(inputStream != null)

              result = convertInputStreamToString(inputStream);

          else

              result = “Did not work!”;


      }

      catch (Exception e) {

          Log.d(“InputStream”, e.getLocalizedMessage());

      }

      return result;

  }

  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;

  }

}

java\com.gantasoft.recylerlist\UserDTO.java

 

package com.gantasoft.recylerlist;


public class UserDTO {

String user_id,user_name,user_email;


  public String getUser_id() {

      return user_id;

  }


  public void setUser_id(String user_id) {

      this.user_id = user_id;

  }


  public String getUser_name() {

      return user_name;

  }


  public void setUser_name(String user_name) {

      this.user_name = user_name;

  }


  public String getUser_email() {

      return user_email;

  }


  public void setUser_email(String user_email) {

      this.user_email = user_email;

  }

}

 

java\com.gantasoft.recylerlist\UserOBJ.java

package com.gantasoft.recylerlist;


public class UserOBJ {

String user_id,user_name,user_email;


  public UserOBJ(String user_id, String user_name, String user_email) {

      this.user_id = user_id;

      this.user_name = user_name;

      this.user_email = user_email;

  }


  public String getUser_id() {

      return user_id;

  }


  public void setUser_id(String user_id) {

      this.user_id = user_id;

  }


  public String getUser_name() {

      return user_name;

  }


  public void setUser_name(String user_name) {

      this.user_name = user_name;

  }


  public String getUser_email() {

      return user_email;

  }


  public void setUser_email(String user_email) {

      this.user_email = user_email;

  }

}

build.gradle

apply plugin: ‘com.android.application’


android {

  compileSdkVersion 28

  defaultConfig {

      applicationId “com.gantasoft.recylerlist”

      minSdkVersion 15

      targetSdkVersion 28

      versionCode 1

      versionName “1.0”

      testInstrumentationRunner “android.support.test.runner.AndroidJUnitRunner”

  }

  buildTypes {

      release {

          minifyEnabled false

          proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’

      }

  }

}


dependencies {

  implementation fileTree(dir: ‘libs’, include: [‘*.jar’])

  implementation ‘com.android.support:appcompat-v7:28.0.0’

  implementation ‘com.android.support.constraint:constraint-layout:1.1.3’

  testImplementation ‘junit:junit:4.12’

  implementation ‘com.android.support:cardview-v7:28.0.0-alpha3’

  implementation ‘com.google.code.gson:gson:2.2.4’

  implementation ‘com.android.support:recyclerview-v7:28.0.0-alpha3’

  androidTestImplementation ‘com.android.support.test:runner:1.0.2’

  androidTestImplementation ‘com.android.support.test.espresso:espresso-core:3.0.2’

}

res\layout\activity_main.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”

  tools:context=“.MainActivity”>

<LinearLayout

  android:layout_width=“match_parent”

  android:layout_height=“match_parent”>

  <android.support.v7.widget.RecyclerView

      android:layout_width=“match_parent”

      android:id=“@+id/recyler”

      android:layout_height=“match_parent”></android.support.v7.widget.RecyclerView>

</LinearLayout>


</android.support.constraint.ConstraintLayout>

res\layout\recycler.xml

<?xml version=“1.0” encoding=“utf-8”?>

<android.support.v7.widget.CardView android:id=“@+id/card_view”

  android:layout_width=“match_parent”

  android:layout_height=“match_parent”

  android:layout_gravity=“center”

  android:layout_margin=“10dp”

  android:elevation=“3dp”

  card_view:cardCornerRadius=“10dp”

  xmlns:android=“http://schemas.android.com/apk/res/android”

  xmlns:card_view=“http://schemas.android.com/apk/res-auto”>


  <LinearLayout

      android:layout_width=“match_parent”

      android:orientation=“vertical”

      android:layout_height=“wrap_content”>

      <TextView

          android:layout_width=“match_parent”

          android:id=“@+id/text”

          android:layout_height=“wrap_content” />

      <TextView

          android:layout_width=“match_parent”

          android:id=“@+id/text2”

          android:layout_height=“wrap_content” />




  </LinearLayout>


</android.support.v7.widget.CardView>