API Retrofit2 Save Response in string then convert to json

 

Security Reason solve 

Add Code

android:usesCleartextTraffic="true"

How to add internet permission in AndroidManifest.xml in android studio.

Step 1 :

Go to app -> src -> main -> AndroidManifest.xml.

Step 2:

Copy following code:

To add a dependency to your project, specify a dependency configuration such as implementation in the dependencies block of your module's build.gradle file.

For example, the following build.gradle file for an app module includes three different types of dependencies:


plugins {
  id
'com.android.application'
}

android
{ ... }

dependencies
{
   
// Dependency on a local library module for retrofit2
   implementation 'com.squareup.retrofit2:retrofit:2.7.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.7.2'
    implementation 'com.squareup.okhttp3:okhttp:3.6.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
//update
implementation("com.squareup.retrofit2:converter-gson:2.7.2")
implementation("com.squareup.okhttp3:okhttp:3.6.0")
implementation("com.squareup.retrofit2:converter-scalars:2.9.0")
implementation ("com.squareup.picasso:picasso:2.8")
implementation ("com.squareup.retrofit2:retrofit:2.9.0")
}

Create Api Function Step 1

Step 2: ( public Call<String> get();)

use Retrofit Calling  this function public Call<String> get()

Request body

If the JSON data describes an array, and each element of that array is an object:

[
  {
    "id": 0,
    "sectionOfferId": [
      0
    ],
    "studentID": "string",
    "discipline": "string"
  }
]

the JSON Data Set will create a row for each object in the array, and each property on the object will become a column. 

send Intent Array of Object 

app/src/main/java/com/example/app/Intent.java

ArrayList<Integer> selectCourse= new ArrayList<>();                   
  JSONArray jsonArray = new JSONArray();ArrayList<Integer> selectCourse= new ArrayList<>();
JSONObject jsonObject = new JSONObject();
jsonArray.put(jsonObject);
try {
jsonObject.put("id", binding.spinnerDiscipline.getSelectedItem());
jsonObject.put("sectionOfferId", selectCourse);
// jsonObject.put("studentID", "string");
// jsonObject.put("discipline", "string");
} catch (JSONException e) {
e.printStackTrace();
}
// jsonArray.put(jsonObject);
// String sendDataIntent=
Gson gson= new Gson();
// Toast.makeText(AdminSettingAssignCourseActivity.this, ""+jsonArray.toString(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),AdminSettingAssignCourseAssignStudentActivity.class);
intent.putExtra("Data",jsonArray.toString());
startActivity(intent);

app/src/main/java/com/example/app/LatestCheck.java

package com.example.quanta;

import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.quanta.adapter.ListShowAdapter;
import com.example.quanta.model.Shop;
import com.google.gson.Gson;
import com.example.quanta.api.Api;
import com.example.quanta.databinding.ActivitySplashScreenBinding;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;


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

import java.lang.reflect.Type;
import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class SplashScreenActivity extends AppCompatActivity {
ActivitySplashScreenBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding= ActivitySplashScreenBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();

Api api = retrofit.create(Api.class);
api.GetData(40.7128f,40.7128f).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
String json = response.body().toString();
// Parse the JSON string to a JsonObject
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();


//
// Get the JSON array from the JsonObject using the correct key
JsonObject firstObject = jsonObject.getAsJsonObject("data").getAsJsonObject("shops");
JsonArray dataArray = firstObject.getAsJsonArray("data");
Type userListType = new TypeToken<ArrayList<Shop>>(){}.getType();
Gson gson= new Gson();
ArrayList<Shop> ShopList = new ArrayList<>();
ShopList.addAll(gson.fromJson(dataArray, userListType));

ListShowAdapter adapter = new
ListShowAdapter(ShopList, getApplicationContext());
LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext());
binding.RecycerviewAdminHome.setLayoutManager(manager);
binding.RecycerviewAdminHome.setHasFixedSize(true);
binding.RecycerviewAdminHome.
setAdapter(adapter);
// binding.txtViewShow.setText(response.body());
Toast.makeText(SplashScreenActivity.this, ""+ShopList.get(9).getAddress(), Toast.LENGTH_SHORT).show();
}
// Toast.makeText(SplashScreenActivity.this, ""+response.code(), Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(SplashScreenActivity.this, ""+t, Toast.LENGTH_SHORT).show();
}
});

}
}

Get Intent Array of Object 

app/src/main/java/com/example/app/Intent.java

setContentView(binding.getRoot());
JSONArray jsonArray = null;
String IntentData=getIntent().getStringExtra("Data");
try {
jsonArray = new JSONArray(IntentData);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Toast.makeText(this, ""+jsonObject.getString("sectionOfferId"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}

Use JSONObject to send List  Intent 

Code JSONObject

                    JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonArray.put(jsonObject);
//search ID List
// int secID = 0; // set a default value if no matching SectionOffer is found
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
// secID = sectionOffers.stream()
// .filter(s -> s.getDiscipline().contains(binding.spinnerDiscipline.getSelectedItem().toString()))
// .findFirst()
// .map(SectionOffer::getId)
// .orElse(-1);
// }
// Toast.makeText(AdminSettingAssignCourseActivity.this, ""+ secID, Toast.LENGTH_SHORT).show();


try {
Gson gson= new Gson();
jsonObject.put("id", 0);
jsonObject.put("sectionOfferId",gson.toJson(selectCourseObj));
jsonObject.put("discipline", binding.spinnerDiscipline.getSelectedItem());
//
} catch (JSONException e) {
e.printStackTrace();
}

// Toast.makeText(AdminSettingAssignCourseActivity.this, ""+jsonArray.toString(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),AdminSettingAssignCourseAssignStudentActivity.class);
intent.putExtra("Data",jsonArray.toString());
startActivity(intent);

Use JSONArray to get List  Intent 

Code JSONArray

JSONArray jsonArrayIntent = null;
JSONArray jsonArraySentApi = null;
JSONObject jsonObjectIntent=null;
ArrayList<SectionOffer> sectionOffers;
ArrayList<Integer> selectCourseID= new ArrayList<>();

String IntentData=getIntent().getStringExtra("Data");
try {
jsonArrayIntent = new JSONArray(IntentData);
jsonArraySentApi = new JSONArray();
jsonObjectIntent = jsonArrayIntent .getJSONObject(0);

// JSONArray jsonArrayObj = new JSONArray(jsonObject.getString("sectionOfferId"));
Gson gson = new Gson();
sectionOffers=gson.fromJson(jsonObjectIntent.getString("sectionOfferId"), new TypeToken<ArrayList<SectionOffer>>(){}.getType());
for (SectionOffer sectionO:sectionOffers) {
selectCourseID.add(sectionO.getId());
}
// Toast.makeText(this, ""+sectionOffers.get(0).courseCode, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}

Use RecyclerView Click item  to Store  JSONArray List  And Remove JSONObject 

Code JSONArray

ArrayList<Student> students= new ArrayList<>();
public void RecyclerviewAssignCourseSelectStudent(Student obj, Context context, String Select) {
// Toast.makeText(context, "jj", Toast.LENGTH_LONG).show();
if(Select.contains("Add")){
students.add(obj);

try {
JSONObject jsonObjectSelect = new JSONObject(jsonObjectIntent.toString());
JSONArray array= new JSONArray(selectCourseID.toString());
jsonObjectSelect.put("sectionOfferId",array);
jsonObjectSelect.put("studentID", obj.getAridNo());
jsonArraySentApi.put(jsonObjectSelect);
Toast.makeText(context, jsonArraySentApi.toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
binding.searchBar.setText(jsonArraySentApi.toString());
}else{
for (int i = 0; i < jsonArraySentApi.length(); i++) {
try {
if (jsonArraySentApi.getJSONObject(i).getString("studentID").contains(obj.getAridNo())) {
jsonArraySentApi.remove(i);
}
} catch (JSONException e) {
e.printStackTrace();
}

}
}
}

Send Data Api Use JSONArray  and Api Function 

@GET("api/dvr-details")
public Call<String> api_dvr_details_String();

  //api calling send data

binding.floatingBtnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonArraySentApi.toString());
Toast.makeText(getApplicationContext(), ""+jsonArraySentApi, Toast.LENGTH_SHORT).show();
api.student_enroll(requestBody).enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
// binding.searchBar.setText(response.code());
Toast.makeText(AdminSettingAssignCourseAssignStudentActivity.this, ""+response.code(), Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(Call<String> call, Throwable t) {
// binding.searchBar.setText(t.toString());
// Toast.makeText(AdminSettingAssignCourseAssignStudentActivity.this, ""+t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
});

Get Data Api Use JSONArray  and Api Function 

@POST("api/student-enroll")
public Call<String> student_enroll(@Body RequestBody jsonArray);

       ArrayList<JSONObject> jsonlist=new ArrayList<>();
        Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();

Api api = retrofit.create(Api.class);
 //api calling send data
api.api_dvr_details_String().enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()){
// Toast.makeText(notification.this, ""+response.body(), Toast.LENGTH_SHORT).show();
try {
JSONArray jsonArray= new JSONArray(response.body().toString());

for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
jsonlist.add(jsonObject);
}
// not working// ArrayList<JSONObject> list= new Gson().fromJson(jsonArray.toString(),new TypeToken<ArrayList<JSONObject>>(){}.getType());
} catch (JSONException e) {
Toast.makeText(notification.this, ""+e, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//recyclerView calling Code
// DVRApapter dvrApapter= new DVRApapter(jsonlist,getApplicationContext());
// RecyclerView recyclerView= findViewById(R.id.recycler_view) ;
// LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext());
// recyclerView.setLayoutManager(manager);
// recyclerView.setAdapter(dvrApapter);
}

}

@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(notification.this, ""+t, Toast.LENGTH_SHORT).show();
}
});


// get JSonObject Data And Key
JSONObject obj = jsonlist.get(0);
HashMap<String, Object> keyMap = new HashMap<>();

Iterator<String> keysIterator = obj.keys();
List<String> keyListNEWADD = new ArrayList<>(Arrays.asList("id", "ip", "name", "channel", "host", "password"));
ArrayList<String> keyListADDRunTimeList = new ArrayList<>();

while (keysIterator.hasNext()) {
String key = keysIterator.next();
keyListADDRunTimeList.add(key);
try {
keyMap.put(key, obj.get(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
// Object typeCheck= keyMap.get("id");
// Toast.makeText(context, ""+typeCheck.getClass().getSimpleName(), Toast.LENGTH_SHORT).show();
// textView.setText(keyMap.get(keyListADDRunTimeList.get(0))+"");




Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.