Skip to content

Instantly share code, notes, and snippets.

@anandrex5
Created May 27, 2022 13:17
Show Gist options
  • Save anandrex5/af151d2fa0d3f407687cf1dee43f09f4 to your computer and use it in GitHub Desktop.
Save anandrex5/af151d2fa0d3f407687cf1dee43f09f4 to your computer and use it in GitHub Desktop.
Json Implemetation(Fetch Values)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeightLarge"
>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="@dimen/activity_horizontal_margin"
android:layout_marginEnd="@dimen/activity_horizontal_margin"
android:contentDescription="Icon" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toEndOf="@id/imageView"
android:layout_toRightOf="@id/imageView"
android:gravity="center_vertical"
android:textSize="16sp"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".JsonParser">
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:scrollbars="vertical"
tools:context=".RecyclerViewExample2">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
ArrayList<JsonModel> list;
Context context;
public CustomAdapter(ArrayList<JsonModel> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View listItem= layoutInflater.inflate(R.layout.jsonlist, parent, false);
ViewHolder viewHolder = new ViewHolder(listItem);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
JsonModel jsonModel = list.get(position);
holder.userid.setText(jsonModel.getId());
holder.name.setText(jsonModel.getName());
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView userid, name;
public ViewHolder(@NonNull View itemView) {
super(itemView);
userid=itemView.findViewById(R.id.textview10);
name=itemView.findViewById(R.id.textview11);
}
}
}
{
"users": [
{
"name": "Anand",
"id": "1"
},
{
"name": "Ankit",
"id": "2"
},
{
"name":"abhishek",
"id": "3"
}
]
}
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class JsonModel {
private String name;
private String id;
public JsonModel(String name, String id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class JsonRecyclerView extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<String> personNames = new ArrayList<>();
ArrayList<String> userId = new ArrayList<>();
ArrayList<JsonModel> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_recycler_view);
recyclerView = findViewById(R.id.recyclerView2);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
CustomAdapter customAdapter = new CustomAdapter(list, this);
recyclerView.setAdapter(customAdapter);
try {
JSONObject obj = new JSONObject(loadJSONfromAssets());
JSONArray userArray = obj.getJSONArray("users");
JsonModel object;
JSONObject userDetails;
Gson gson = new Gson();
for ( int i=0 ; i<userArray.length(); i++){
userDetails = userArray.getJSONObject(i);
object = gson.fromJson(userDetails.toString(), JsonModel.class);
// personNames.add(userDetails.getString("name"));
// userId.add(userDetails.getString("id"));
list.add(object);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String loadJSONfromAssets() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.getClass();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
}
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button button1,buttonn;
private Bundle args;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// toolbar =findViewById(R.id.myToolBar);
// setSupportActionBar(toolbar);
buttonn = findViewById(R.id.buttonn);
buttonn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, JsonRecyclerView.class);
startActivity(intent);
}
});
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragmentContainerView,new MainFragment()).commit();
FragmentManager fragmentManager1 = getSupportFragmentManager();
fragmentManager1.beginTransaction()
.replace(R.id.abc,new MainFragment2()).commit();
}
}
//Switch Button to Activity
// Log.v("activity_lifestyle","OnCreate1 called");
// button = (Button) findViewById(R.id.button);
// button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
//
//
// }
// }
// @Override
// protected void onStart() {
// super.onStart();
// Log.v("activity_lifestyle","OnStart1 called");
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// Log.v("activity_lifestyle","OnResume1 called");
// }
//
// @Override
// protected void onPause() {
// super.onPause();
// Log.v("activity_lifestyle","OnPause1 called");
// }
//
// @Override
// protected void onStop() {
// super.onStop();
// Log.v("activity_lifestyle","OnStop1 called");
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// Log.v("activity_lifestyle","OnDestroy1 called");
// printLinkedList();
//Parcelable
// Animals obj2=new Animals();
// obj2.setName1("Lion");
// obj2.setFunctinalities("Hunt");
//
// Intent intent = new Intent(MainActivity.this,ThirdActivity.class);
// intent.putExtra("Mammals",obj2);
// startActivity(intent);
//Serializable
// Employees model = new Employees();
// model.setId(755);
// model.setName("Anand");
//
// Intent intent= new Intent(MainActivity.this,SecondActivity.class);
// intent.putExtra("Human", model);
// startActivity(intent);
//PrintAbstractionClass();
//MultilevelInheritanceClass();
//HierarchicalInheritanceClass();
//SingleInheritanceClass();
//HybridInheritanceClass();
//PolymorphimClass();
//OverRidingClass();
//OverloadingClass();
//EncapsulationClass();
//InterafaceClass();
//ConstructorClass();
//DefaulConstructorClass();
//ParameterizedConstructorClass();
//printArrayList();
//printArray();
//printStringBuffer();
//printStringBuilder();
// private void printLinkedList() {
//
// LinkedList<String> al = new LinkedList<String>();
// al.add("Ravi");
// al.add("Vijay");
// al.add("Ravi");
// al.add("Ajay");
//
// Iterator<String> itr = al.iterator();
// while (itr.hasNext()) {
// Toast.makeText(this, "" + itr.next(), Toast.LENGTH_SHORT).show();
// }
// }
// private void printStringBuilder() {
// StringBuilder builder=new StringBuilder("Welcome");
// builder.append("User");
// Toast.makeText(this, ""+builder, Toast.LENGTH_SHORT).show();
// }
// //printStringBuffer();
// private void printStringBuffer() {
// StringBuffer buffer=new StringBuffer("Welcome");
// buffer.append("User");
// Toast.makeText(this, ""+buffer, Toast.LENGTH_SHORT).show();
// }
// //array
// private void printArray() {
//
// int[] arr = new int[3];
// arr[0] = 5;
// arr[1] = 6;
// arr[2] = 10;
//
// Toast.makeText(this, ""+ Arrays.toString(arr), Toast.LENGTH_SHORT).show();
// }
// //ArrayList
// private void printArrayList() {
// ArrayList<Integer> arr = new ArrayList<Integer>();
// arr.add(5);
// arr.add(9);
// arr.add(11);
//
// Toast.makeText(this, ""+arr, Toast.LENGTH_SHORT).show();
//
// }
// //Parameterized Constructor
// private void ParameterizedConstructorClass() {
// Main2 myObj = new Main2(5);
// Log.v(Main2.class.getSimpleName(), "myObj" + (myObj.x));
// }
//
//
// public class Main2 {
// int x;
//
// public Main2(int y) {
// x = y;
// }
//
// }
//
//
// //Default Constructor
// private void DefaulConstructorClass() {
// new Demo();
// }
//
// class Demo {
// public Demo() {
// Log.v(Demo.class.getSimpleName(), "This is a no argument constructor");
// }
//
// }
//
//
// //constructor
//
// private void ConstructorClass() {
// Hello obj = new Hello();
// Log.v(Hello.class.getSimpleName(), "Hello Google");
// }
//
// public class Hello {
// String name;
//
// //Constructor
// Hello() {
// this.name = "Google.com";
// }
// }
//
//
// //Interface
// private void InterafaceClass() {
//
// Mammals i = new Mammals();
// i.eat();
// i.travel();
// }
//
//
// //overiding
// private void OverloadingClass() {
// Adder adder = new Adder();
// Toast.makeText(MainActivity.this, "" + adder.add(10, 20), Toast.LENGTH_SHORT).show();
// Toast.makeText(this, "" + adder.add(12.3, 12.6), Toast.LENGTH_SHORT).show();
// }
//
// class Adder {
// int add(int a, int b) {
// return a + b;
// }
//
// double add(double a, double b) {
// return a + b;
// }
// }
//
//
// //overiding
// private void OverRidingClass() {
// Car b = new Audi();//upcasting
// b.run();
// }
//
// class Car {
// void run() {
// System.out.println("running");
// }
// }
//
// class Audi extends Car {
// void run() {
// Toast.makeText(MainActivity.this, "running safely with 200km", Toast.LENGTH_SHORT).show();
// }
// }
//
//
// //polymorphism
// private void PolymorphimClass() {
// Animal myAnimal = new Animal(); // Create a Animal object
// Animal myPig = new Pig(); // Create a Pig object
// Animal myDog = new Dog(); // Create a Dog object
// myAnimal.animalSound();
// myPig.animalSound();
// myDog.animalSound();
// }
//
// class Animal {
// public void animalSound() {
// Toast.makeText(MainActivity.this, "The animal makes a sound", Toast.LENGTH_SHORT).show();
// }
// }
//
// class Pig extends Animal {
// public void animalSound() {
// Toast.makeText(MainActivity.this, "The pig says: wee wee", Toast.LENGTH_SHORT).show();
// }
// }
//
// class Dog extends Animal {
// public void animalSound() {
// Toast.makeText(MainActivity.this, "The dog says: bow wow\"", Toast.LENGTH_SHORT).show();
// }
// }
//
// class Main1 {
// }
//
//
// //hybrid
// private void HybridInheritanceClass() {
// Daughter1 obj = new Daughter1();
// obj.show();
// }
//
// class GrandFather {
// public void show() {
// Toast.makeText(MainActivity.this, "I am grandfather.", Toast.LENGTH_SHORT).show();
// }
// }
//
// //inherits GrandFather properties
// class Father extends GrandFather {
// public void show() {
// Toast.makeText(MainActivity.this, "I am father.", Toast.LENGTH_SHORT).show();
// }
// }
//
// //inherits Father properties
// class Son extends Father {
// public void show() {
// Toast.makeText(MainActivity.this, "I am son.", Toast.LENGTH_SHORT).show();
// }
// }
//
// //inherits Father properties
// public class Daughter1 extends Father {
// public void show() {
// Toast.makeText(MainActivity.this, "I am a daughter.", Toast.LENGTH_SHORT).show();
// }
//
//
// //Hierarchical
// private void HierarchicalInheritanceClass() {
// Son s = new Son();
// Daughter1 d = new Daughter1();
// }
//
// class Father1 {
// String familyName;
// String houseaddress;
//
// Father1() {
// familyName = "Programmer";
// houseaddress = "Delhi";
// }
// }
//
// class Son extends Father1 {
// Son() {
// Toast.makeText(MainActivity.this, "I am the Son", Toast.LENGTH_SHORT).show();
// Toast.makeText(MainActivity.this, "My family name is \" + this.familyName + \" and I am from \" + this.houseaddress", Toast.LENGTH_SHORT).show();
// }
// }
//
// class Daughter extends Father1 {
// Daughter() {
// Toast.makeText(MainActivity.this, "I am the Daughter", Toast.LENGTH_SHORT).show();
// Toast.makeText(MainActivity.this, "My family name is \" + this.familyName + \" and I am from \" + this.houseaddress", Toast.LENGTH_SHORT).show();
// }
// }
//
//
// //single inheritance
// private void SingleInheritanceClass() {
// Rectangle rect = new Rectangle();
// rect.display();
// rect.area();
// }
//
// class Shape {
// public void display() {
// Toast.makeText(MainActivity.this, "Inside display", Toast.LENGTH_SHORT).show();
// }
// }
//
// class Rectangle extends Shape {
// public void area() {
// Toast.makeText(MainActivity.this, "Inside area", Toast.LENGTH_SHORT).show();
// }
// }
//
// public class Tester {
// }
//
//
// //Multilevel
// private void MultilevelInheritanceClass() {
// Son1 s1 = new Son1();
// }
//
// class GrandFather {
// GrandFather() {
// Toast.makeText(MainActivity.this, "I am the grandfather!", Toast.LENGTH_SHORT).show();
// }
// }
//
// class Father extends GrandFather {
// String familyName;
// String houseaddress;
//
// Father() {
// Toast.makeText(MainActivity.this, "I am the father! I inherit from Grandfather", Toast.LENGTH_SHORT).show();
// }
// }
//
// public class Son1 extends Father {
// Son1() {
// Toast.makeText(MainActivity.this, "I am the son and I inherit from my father.", Toast.LENGTH_SHORT).show();
// }
//
//
// //Abstraction
// private void PrintAbstractionClass() {
// Dog d1 = new Dog();
//
// d1.makeSound();
// d1.eat();
// }
//
// abstract class Animal {
// abstract void makeSound();
//
// public void eat() {
// Toast.makeText(MainActivity.this, "Bark bark", Toast.LENGTH_SHORT).show();
// }
// }
//
// class Dog extends Animal {
//
// // provide implementation of abstract method
// public void makeSound() {
// Toast.makeText(MainActivity.this, "My name is Anand", Toast.LENGTH_SHORT).show();
// }
// }
//
// }
//
// }
//}
@anandrex5
Copy link
Author

anandrex5 commented May 31, 2022

Add dependencies --

build.gridle file-

plugins {
id 'com.android.application'
}

android {
compileSdk 32

defaultConfig {
    applicationId "com.example.myapplication"
    minSdk 21
    targetSdk 32
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

}

dependencies {

implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.fragment:fragment:1.3.5'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation "androidx.cardview:cardview:1.0.0"
implementation "androidx.recyclerview:recyclerview:1.2.1"
implementation 'com.google.code.gson:gson:2.8.7'

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment