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:
< uses -permission android : name ="android.permission.INTERNET" />
<uses-permission android :name ="android.permission.CAMERA" />
Dependency types 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.camera3.api ;
import android.content.Context; import android.net.Uri; import androidx.annotation.NonNull ; import com.example.camera3.model.ExampleModel; import java.io.File; import java.io.IOException; import java.util.ArrayList; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.http.GET ; import retrofit2.http.POST ; public interface Api { public static String BASE_URL ="http://192.168.100.13:8000/" ; // public static String // IMAGE_BASE_URL="http://192.168.136.33/FYPApi/"; // @POST("Customer/SaveCustomer") // public Call<String> saveCustomer(@Body Customer c); @GET ("api/user-details" ) public Call<ArrayList<ExampleModel>> getModel (); @GET ("api/user-details" ) public Call<String> get (); // // @GET("math/getusers") // public Call<List<User>> getUsers(); // // @GET("math/divide") // public Call<Integer> divide(@Query("n1") int n1, @Query("n2") int n2); // // @GET("Customer/getallcustomers") // public Call<ArrayList<Customer>> getAllCustomers(); // // @GET("Customer/getAllProfiles") // public Call<ArrayList<UserProfileInfo>> getAllProfile(); // // @Multipart // @POST("Customer/uploadImage") // public Call<String> saveUserProfile // ( // @Part ArrayList<MultipartBody.Part> images, // @Part("id") RequestBody id, // @Part("lname") RequestBody lname, // @Part("fname") RequestBody fname, // @Part("address") RequestBody address, // @Part("gender") RequestBody g // ); @NonNull public default MultipartBody.Part prepareFilePart (String partName, Uri fileUri, Context context) throws IOException { File file = FileUtil.from (context, fileUri); RequestBody requestFile = RequestBody.create ( MediaType.parse (context.getContentResolver().getType(fileUri)), file ); return MultipartBody.Part.createFormData (partName, file.getName(), requestFile); } public default RequestBody createPartFromString (String descriptionString){ RequestBody description = RequestBody.create ( okhttp3.MultipartBody.FORM , descriptionString); return description; } }
Step 2: ( public Call<String> get () ;) use Retrofit Calling this function public Call<String> get ()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.example.camera3; import androidx.appcompat.app.AppCompatActivity; import android.media.session.MediaController; import android.os.Bundle; import android.widget.Toast; import android.widget.VideoView; import com.example.camera3.api.Api; import com.example.camera3.databinding.ActivityVideoplayBinding; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.scalars.ScalarsConverterFactory; public class videoplay extends AppCompatActivity { ActivityVideoplayBinding binding ; private VideoView mVideoView ; private MediaController mMediaController ; public class User { public String userID ; public String user ; // add getters and setters for each field } @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState); binding =ActivityVideoplayBinding.inflate (getLayoutInflater()); setContentView(binding .getRoot()); // exist key check // String jsonData = "{\"Requests\":[],\"Id\":1,\"Name\":null,\"Cnic\":null,\"Phonenumber\":null,\"Fikkah\":null,\"Password\":\"password\",\"Image\":null,\"Email\":\"test@example.com\",\"Location\":null,\"Gender\":null}"; // // JSONObject jsonObj = new JSONObject(jsonData); // boolean schedulesExist = jsonObj.has("Schedules"); // // if (schedulesExist) { // System.out.println("The 'Schedules' key exists in the JSON data."); // } else { // System.out.println("The 'Schedules' key does not exist in the JSON data."); // } Retrofit retrofit = new Retrofit.Builder() .baseUrl(Api.BASE_URL ) .addConverterFactory(ScalarsConverterFactory.create ()) .build(); Api api = retrofit.create(Api.class ); api.get().enqueue(new Callback<String>() { @Override public void onResponse (Call<String> call, Response<String> response) { if (response.isSuccessful()) { String json = response.body().toString(); // String inputString = "AbcDefgHijKlmnOpqRsTuVwXyz"; // String regexString = "^\\s\"\\s[a-zA-Z]\\s\"\\s+$"; // boolean KeyMatches = json.matches(regexString); if (json.startsWith("{" )) { String json2 = "{ \n " + " \" data \" : [ \n " + " { \n " + " \" id \" : 1, \n " + " \" ip \" : \" 192.168.1.1 \" , \n " + " \" name \" : \" Admin \" , \n " + " \" channel \" : \" 5 \" , \n " + " \" host \" : \" Admin \" , \n " + " \" password \" : \" Admin \"\n " + " } \n " + " ] \n " + "}" ; JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(json2).getAsJsonObject(); JSONArray dataArray = jsonObject.getJSONArray( "data" );
JSONObject firstObject = dataArray.getJSONObject( 0 );
String ip = firstObject.getString( "ip" ); Map <String , ArrayList<DVR>> map ; Gson gson = new Gson() ; Type type = new TypeToken<Map<String , ArrayList<DVR>>>(){}.getType() ; map = gson.fromJson(json2 , type) ; ArrayList<DVR> dvrList = map.get( "data" ) ; System. out .println( "IP show+" +dvrList.get( 0 ).getIp()) ; //single object get // Customer u= g.fromJson(s, Customer.class); Toast. makeText (videoplay. this, "Object" , Toast. LENGTH_SHORT ).show() ; } else if (json.startsWith( "[" )) { try { Gson gson = new Gson() ; Type userListType = new TypeToken<List<User>>(){}.getType() ; List<User> users = gson.fromJson(json , userListType) ; Toast. makeText (videoplay. this, "List item 0 Name" +users.get( 0 ). userID , Toast. LENGTH_SHORT ).show() ; } catch (Exception e){ System. out .println( "" +e.toString()) ; } } else if (json.startsWith( " \" " )) { Toast. makeText (videoplay. this, "String" , Toast. LENGTH_SHORT ).show() ; } else { // inputString contains non-alphabetic characters } // do something with the response string } else { // handle the error } } @Override public void onFailure (Call<String> call , Throwable t) { } }) ; } }
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))+"");