Problem to implement API in Android Studio - java

I need help to implement a list view from an API,
i need one more list to complete and make a get method.
This is for a project for faculty and i dont see solution on tutorials on internet
Here is code for information view :
package com.example.myapplication;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.common.api.Api;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.io.File;
import java.io.IOException;
import javax.net.ssl.HttpsURLConnection;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class TopScorer extends AppCompatActivity {
SearchView searchView;
ListView listView;
String teams[] = {};
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_scorer);
searchView = findViewById(R.id.search);
listView = findViewById(R.id.listview);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
ArrayList<String> teamsInf = new ArrayList<>();
#Override
public boolean onQueryTextSubmit(String query) {
API API = new API(query);
try {
API.execute().get();
teamsInf = API.getTeamsInfo();
arrayAdapter = new ArrayAdapter<String>(TopScorer.this, android.R.layout.simple_list_item_1, teamsInf);
listView.setAdapter(arrayAdapter);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
}
public class API extends AsyncTask {
String teamName;
ArrayList<String> teamsInfo;
public API(String name) {
this.teamsInfo = new ArrayList<>();
}
#Override
protected Object doInBackground(Object[] objects) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://heisenbug-premier-league-live-scores-v1.p.rapidapi.com/api/premierleague/team?name="+this.teamName)
.get()
.addHeader("X-RapidAPI-Key", "6ad8dfcfcbmshb4a45a22532e4a1p1efecajsnc2fb433de0da")
.addHeader("X-RapidAPI-Host", "heisenbug-premier-league-live-scores-v1.p.rapidapi.com")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
Toast.makeText(TopScorer.this, "Error", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
int index=1;
String myResult = response.body().string();
Gson gson = new Gson();
Data responseResult=gson.fromJson(myResult, Data.class);
for (lst l : responseResult.Data())
{
Log.d(TAG, "Liverpool: " + l.getTeam());
teamsInfo.add(String.valueOf(index) + ". " + l.getPlayed() + ": " + l.getWin());
teamsInfo.add("Draws : " + l.getDraw());
teamsInfo.add("Loss : " + l.getLoss());
teamsInfo.add("Goals Against : " + l.getGoalsAgainst());
teamsInfo.add("Goals For : " + l.getGoalsFor());
teamsInfo.add("Points : " + l.getPoints());
teamsInfo.add("");
index++;
}
}
});
return null;
}
public ArrayList<String> getTeamsInfo()
{
return this.teamsInfo;
}
}
}
and here is Data Class code:
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Data {
private String team;
private String played;
private String win;
private String draw;
private String loss;
private String goalsFor;
private String goalsAgainst;
private String points;
public String getTeam() {
return this.team;
}
public String getPlayed() {
return this.played;
}
public String getWin() {
return this.win;
}
public String getDraw() {
return this.draw;
}
public String getLoss() {
return this.loss;
}
public String getGoalsFor() {
return this.goalsFor;
}
public String getGoalsAgainst() {
return this.goalsAgainst;
}
public String getPoints() {
return this.points;
}
public Data fromJson(JSONObject jsonObject) {
Data team = new Data();
try {
team.team = jsonObject.getString("team");
team.played = jsonObject.getString("played");
team.win = jsonObject.getString("win");
team.draw = jsonObject.getString("draw");
team.loss = jsonObject.getString("loss");
team.goalsFor = jsonObject.getString("goalsFor");
team.goalsAgainst = jsonObject.getString("goalsAgainst");
team.points = jsonObject.getString("points");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return team;
}
}
can anyone help me, i prefered to implement api respone with okhttp code

Related

Unable to call api using retrofit in android

Earlier i was able to call api using this code and but now it is not working
I'm not sure that what went wrong so if you can help it will be great.
i have uploaded my code files of circulareNotice.java,api.java and Retrofitclient.java
check the code and let me know that what is error and also solution of that error.
circularNotice.java
package com.example.college_connect_faculty;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.textclassifier.ConversationActions;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.RemoteMessage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class circularNotice extends AppCompatActivity {
EditText noticetxt,noticeTitle;
Button noticeBtn;
TextView stringLength;
String topic = "com.example.college_connect_faculty";
#Override
protected void onCreate(Bundle savedInstanceState) {
FirebaseApp.initializeApp(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_circular_notice);
FirebaseMessaging.getInstance().subscribeToTopic("all");
noticetxt = findViewById(R.id.noticetxt);
noticeBtn = findViewById(R.id.noticeBtn);
stringLength = findViewById(R.id.stringLength);
noticeTitle = findViewById(R.id.noticeTitle);
noticetxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
String s = noticetxt.getText().toString();
int l = s.length();
stringLength.setText(String.valueOf(l));
}
});
noticeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String notice = noticetxt.getText().toString();
String title = noticeTitle.getText().toString();
try {
Call<ResponseBody> call = RetrofitClient.getInstance().getApi().noticeUpload(notice, title);
call.enqueue(new Callback<ResponseBody>() {
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String s = response.body().string();
Toast.makeText(circularNotice.this, s, Toast.LENGTH_SHORT).show();
FcmNotificationsSender notificationsSender = new FcmNotificationsSender("/topics/all",
title, notice, getApplicationContext(), circularNotice.this);
notificationsSender.SendNotifications();
FirebaseMessaging firebaseMessaging = FirebaseMessaging.getInstance();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}catch (Exception e){
Toast.makeText(circularNotice.this,e.getMessage().toString(),Toast.LENGTH_SHORT).show();
}
}
});
}
}
api.java
package com.example.college_connect_faculty;
import java.util.TreeMap;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface api {
#FormUrlEncoded
#POST("uploadSubjects.php")
Call<ResponseBody>uploadSubject(
#Field("semester") String semester,
#Field("branch") String branch,
#Field("subject")String subject
);
#FormUrlEncoded
#POST("showSubjects.php")
Call<ResultSubject> showSubject(
#Field("semester") String semester,
#Field("branch") String branch
);
#Multipart
#POST("filesUpload.php")
Call<ResponseBody> fileUpload(
#Part MultipartBody.Part fileName,
#Part("branch") RequestBody branch,
#Part("semester") RequestBody semester,
#Part("subject") RequestBody subject
);
#FormUrlEncoded
#POST("noticeUpload.php")
Call<ResponseBody> noticeUpload(
#Field("notice") String notice,
#Field("title") String title
);
}
Retrofitclient.java
package com.example.college_connect_faculty;
import android.content.Context;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
static Context context;
final String BASE_URL = "http://192.168.153.223/college_connect/";
private static RetrofitClient mInstance;
Retrofit retrofit;
RetrofitClient(){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized RetrofitClient getInstance(){
if (mInstance==null){
mInstance = new RetrofitClient();
}
return mInstance;
}
public api getApi(){
return retrofit.create(api.class);
}
}
i have checked my ipv4. No problems in it
refer to this answer for a solution
https://stackoverflow.com/a/53984915/5035015
for more information regarding Network security configuration, refer to the below link
https://developer.android.com/training/articles/security-config

Im getting this error while trying to get data from JSON

package com.joshbradley.pokemonapp.activities;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.joshbradley.pokemonapp.R;
import com.joshbradley.pokemonapp.adapters.Adapter;
import com.joshbradley.pokemonapp.helperclass.HelperClass;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HomeScreen extends AppCompatActivity {
//VARIABLES
RecyclerView recyclerView;
List<HelperClass> helperClasses;
Adapter adapter;
private static String JSON_URL_TEST = "https://pokeapi.co/api/v2/pokemon?limit=151";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
//RECYCLER AND VIEW
recyclerView = findViewById(R.id.home_screen_recycler);
helperClasses = new ArrayList<>();
//CALLING EXTRACT DATA METHOD
extractData();
}
//EXTRACT DATA & REQUESTS
private void extractData() {
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, "https://pokeapi.co/api/v2/pokemon?limit=151", null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
HelperClass helperClass = new HelperClass();
helperClass.setName(jsonObject.getString("name"));
helperClass.setImageUrl(jsonObject.getString("url"));
helperClasses.add(helperClass);
} catch (JSONException e) {
e.printStackTrace();
}
}
//ADAPTER AND LAYOUT MANAGER
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter = new Adapter(getApplicationContext(), helperClasses);
recyclerView.setAdapter(adapter);
}
// ERROR RESPONSE
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
}
}
// MY ERROR
com.android.volley.ParseError: org.json.JSONException: Value {"count":1154,"next":"https:\/\/pokeapi.co\/api\/v2\/pokemon?offset=151&limit=151","previous":null,"results":[{"name":"bulbasaur","url":"https:\/\/pokeapi.co\/api\/v2\/pokemon\/1\/"},{"name":"ivysaur","url":"https:\/\/pokeapi.co\/api\/v2\/pokemon\/2\/"},{"name":"venusaur","url":"https:\/\/pokeapi.co\/api\/v2\/pokemon\/3\/"},
In your extractData() method you have the following which implies that you are expecting the service response to be a JSONArray:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, ...
If you look at the body of the Exception you will see that the service is returning an object (which contains an array).
{ "count":1154
, "next":"https:\/\/pokeapi.co\/api\/v2\/pokemon?offset=151&limit=151"
, "previous":null
, "results":[ ... some array of values]
... you cut it off so there may be more fields ...
}
As such, it looks like you should accept a JSONObject and then extract the value associated with the results key. I'm not sure on the syntax but probably something like...
JsonObjectRequest request = new JsonObjectRequest(...
#Override
public void onResponse(JSONObject response) {
JSONArray results = response.getJSONArray("results");
....

Use Json in Fragment (textView) from OkHttp Request in seperate class

If the button in DietFragment is pressed, it runs the getJson() method in HttpRequestDietPlan. Afterwards the Json(mealId, title) is used in the DietFragment.
Problem: DietFragment doesn't wait for the Request to finish.
Future isn't possible because lowest Android version needs to be 4.4
DietFragment
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DietFragment extends Fragment {
Button button;
TextView mealOne;
public int mealId;
public DietPlan dietPlan = new DietPlan();
HttpRequestDietPlan hrt = new HttpRequestDietPlan();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_diet, null);
ET = rootView.findViewById(R.id.targetCalories_Input);
Tv1 = rootView.findViewById(R.id.targetCalories_Output);
button = rootView.findViewById(R.id.testButton);
mealOne = rootView.findViewById(R.id.meal1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hrt.getJson();
// java.lang.IllegalMonitorStateException: object not locked by thread before wait()
mealId = hrt.dietPlan.meals.get(0).mealId;
title = hrt.dietPlan.meals.get(0).title;
mealOne.setText(title);
}
});
return rootView;
}
}
HttpRequestDietPlan
import android.os.Build;
import android.support.annotation.RequiresApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class HttpRequestDietPlan {
public DietPlan dietPlan = new DietPlan();
public final CompletableFuture<Response> future = new CompletableFuture<>();
public void getJson() {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.addHeader("X-RapidAPI-Host", "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com")
.addHeader("X-RapidAPI-Key", "KEY_KEY_KEY")
.url("https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/mealplans/generate?timeFrame=day&targetCalories=2000")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
try {
String jsonData = response.body().string();
JSONObject json = new JSONObject(jsonData);
JSONArray arrayMeals = json.getJSONArray("meals");
for (int i = 0; i < arrayMeals.length(); i++) {
JSONObject object = arrayMeals.getJSONObject(i);
Meal meal = new Meal(
object.getInt("id"),
object.getString("title")
);
dietPlan.meals.add(meal);
System.out.println(meal);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
}
Here are some suggestions:
You don't need to create a new OkHttpClient at each call, so I moved it outside the method.
Then you can pass a callback (CallHandler) to be notified when the result of the call will be available, and update your data after the result is received.
One more thing, about the deserialization, I suggest you to use a library (https://github.com/google/gson) to deserialize your json response to an instance of a class.
PS: I didn't test this code, this is just a implementation suggestion.
Fragment:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DietFragment extends Fragment {
Button button;
TextView mealOne;
public int mealId;
public DietPlan dietPlan = new DietPlan();
HttpRequestDietPlan hrt = new HttpRequestDietPlan();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_diet, null);
ET = rootView.findViewById(R.id.targetCalories_Input);
Tv1 = rootView.findViewById(R.id.targetCalories_Output);
button = rootView.findViewById(R.id.testButton);
mealOne = rootView.findViewById(R.id.meal1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hrt.getJson(new HttpRequestDietPlan.CallHandler(
#Override
public void onFailure(Exception e) {
e.printStackTrace();
}
#Override
public void onSuccess(DietPlan dietPlan) {
mealId = hrt.dietPlan.meals.get(0).mealId;
title = hrt.dietPlan.meals.get(0).title;
mealOne.setText(title);
}
));
}
});
return rootView;
}
}
HttpRequestDietPlan:
import android.os.Build;
import android.support.annotation.RequiresApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class HttpRequestDietPlan {
private OkHttpClient client = new OkHttpClient();
public interface CallHandler {
public void onSuccess(DietPlan dietPlan);
public void onFailure(Exception e);
}
public void getJson(CallHandler callHandler) {
final Request request = new Request.Builder()
.addHeader("X-RapidAPI-Host", "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com")
.addHeader("X-RapidAPI-Key", "KEY_KEY_KEY")
.url("https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/mealplans/generate?timeFrame=day&targetCalories=2000")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
e.printStackTrace();
callHandler.onFailure(e)
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
IOException e = new IOException("Unexpected code " + response);
callHandler.onFailure(e)
} else {
DietPlan dietPlan = new DietPlan();
// Deserialize with a library here
try {
String jsonData = response.body().string();
JSONObject json = new JSONObject(jsonData);
JSONArray arrayMeals = json.getJSONArray("meals");
for (int i = 0; i < arrayMeals.length(); i++) {
JSONObject object = arrayMeals.getJSONObject(i);
Meal meal = new Meal(
object.getInt("id"),
object.getString("title")
);
dietPlan.meals.add(meal);
System.out.println(meal);
}
} catch (JSONException e) {
e.printStackTrace();
}
callHandler.onSuccess(dietPlan)
}
}
});
}
}

Loading JSON data into alertdialog into spinner

I'm trying to retrieve Json data into a spinner that's in an alertdialog , it only loads if the spinner in the same activity but if it's in an alertDialog it gives me this Error :
Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
package exir.exir;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import exir.exir.Helpers.FormAdapter;
import exir.exir.Helpers.PatientsAdapter;
import exir.exir.Helpers.PricrMAdapter;
import exir.exir.Helpers.RequestHandler;
import exir.exir.Helpers.SharedPrefManager;
import exir.exir.Rertofit.MyLabAPI;
import exir.exir.Utils.Constants;
import exir.exir.model.Form;
import exir.exir.model.PMenus;
import exir.exir.model.PriceM;
import exir.exir.model.RPatient;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import static android.R.layout.simple_spinner_item;
public class AddPatient extends AppCompatActivity {
private EditText patientname, gender , age , agetype , tel ,
phone , total , notes , testno , testprice , testnotes , testname1 , testno1 , testprice1 , testnotes1 ;
private Button add ;
private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
String labId , labpriceMenuNO ;
private static ProgressDialog mProgressDialog;
private ArrayList<PMenus> goodModelArrayList;
private ArrayList<String> names = new ArrayList<String>();
private Spinner PmSpinner;
MyLabAPI myLabAPI ;
CompositeDisposable compositeDisposable = new CompositeDisposable();
List<PriceM> pricemenilist;
ArrayAdapter<String> adapter;
ListView FormList ;
EditText editThen , edtSdt;
Button btn_sua , btn_xoa , btn_then ;
ArrayList<Form> formArrayList ;
FormAdapter formAdapter;
FloatingActionButton newTest ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_patient);
testno = (EditText)findViewById(R.id.testno);
testprice = (EditText)findViewById(R.id.testprice);
testnotes = (EditText)findViewById(R.id.testnotes);
newTest = (FloatingActionButton)findViewById(R.id.
newTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showNewTestDialog();
}
});
myLabAPI = Constants.getAPI();
add =(Button)findViewById(R.id.addPatient);
}
private void showNewTestDialog() {
AlertDialog.Builder alertDialog = new
AlertDialog.Builder(AddPatient.this);
alertDialog.setTitle("Add New Test ");
alertDialog.setMessage("PLease fill the info ");
LayoutInflater inflater = this.getLayoutInflater();
View formLayout = inflater.inflate(R.layout.newtest_layout, null);
editThen = formLayout.findViewById(R.id.FName);
edtSdt = formLayout.findViewById(R.id.FPrice);
goodModelArrayList = new ArrayList<>();
PmSpinner = (Spinner)findViewById(R.id.testname);
PmSpinner.setAdapter(adapter);
PmSpinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
String item = parent.getItemAtPosition(position).toString() ;
String testum = goodModelArrayList.get(position).getCity() ;
String price = goodModelArrayList.get(position).getCountry() ;
testnotes.setText(item);
testno.setText(testum);
testprice.setText(price);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
retrieveJSON();
alertDialog.setView(formLayout);
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
//some code
}
});
alertDialog.setNegativeButton("No", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();
}
private void retrieveJSON() {
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
URLstring,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
goodModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
PMenus playerModel = new PMenus();
JSONObject dataobj =
dataArray.getJSONObject(i);
playerModel.setName(dataobj.getString("name"));
playerModel.setCountry(dataobj.getString("country"));
playerModel.setCity(dataobj.getString("city"));
playerModel.setImgURL(dataobj.getString("imgURL"));
goodModelArrayList.add(playerModel);
}
for (int i = 0; i < goodModelArrayList.size();
i++){
names.add(goodModelArrayList.get(i).getName().toString());
}
ArrayAdapter<String> spinnerArrayAdapter = new
ArrayAdapter<String>(AddPatient.this, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item); // The drop down view
PmSpinner.setAdapter(spinnerArrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Try this.....
JSONObject c = JSONfunctions.getJSONfromURL("http://192.168.1.104/OnlineTicketBooking/book_now1.php?movieid='72'");
try {
JSONArray jarray = c.getJSONArray("offer_detail");
ArrayList<String> xyz= new ArrayList<String>();
for(int i = 0; i < jarray.length(); i++){
JSONArray timeArray = jarray.getJSONObject(i).getJSONArray("showtime");
for(int j = 0; j < timeArray .length(); j++){
xyz.add(timeArray .getString(j));
Log.d("get value",timeArray .getString(j));`enter code here`
}
}

Choreographer Skipped x frames ! The application may be doing too much work on its main thread

I dont understand why the heck this happens?
Anyone has an idea ?
I am trying to send & recieve data from PHP n dynamically append data in xml layout.
Anyone has any idea? The stuff was working well when i just sent the data to PHP using asynctask.
But when i try to recieve and append this logcat gave me heck.
ActivityMain.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.renderscript.Element;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
Button button;
EditText emailBox;
EditText passwordBox;
String emailId;
String passwordId;
private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
#SuppressLint("NewApi") #TargetApi(Build.VERSION_CODES.GINGERBREAD) #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
button = (Button) findViewById(R.id.login1);
emailBox = (EditText)findViewById(R.id.email);
passwordBox = (EditText)findViewById(R.id.password);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP(MainActivity.this).execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void afterEffect(String str){
TextView textV1 = (TextView)findViewById(R.id.textV1);
textV1.setText(str);
}
public void showChatList(JSONArray json){
/*
Document doc;
String fileloc = "C:\\Users\\Admin\\workspace\\myWeb\\res\\layout\\activity_main.xml";
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(fileloc));
//Node nR = doc.getElementById("mainR");
removeChilds(nR);
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
*/
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.mainR);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
LinearLayout LL = new LinearLayout(this);
ImageView pp = new ImageView(this);
TextView name = new TextView(this);
TextView username = new TextView(this);
int generatedId = generateViewId();
pp.setId(generatedId);
LL.setOrientation(LinearLayout.HORIZONTAL);
new ImageLoadTask(pp).execute("http://117.99.55.83/"+c.getString("img"));
name.setText(c.getString("name"));
username.setText(c.getString("username"));
LL.addView(pp);
LL.addView(name);
LL.addView(username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void removeChilds(Node node) {
while (node.hasChildNodes())
node.removeChild(node.getFirstChild());
}
public static int generateViewId() {
for (;;) {
final int result = sNextGeneratedId.get();
// aapt-generated IDs have the high byte nonzero; clamp to the range under that.
int newValue = result + 1;
if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
if (sNextGeneratedId.compareAndSet(result, newValue)) {
return result;
}
}
}
}
toPHP
package com.example.myweb;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
public class toPHP extends AsyncTask<Object, Object, JSONArray>{
final MainActivity main;
public toPHP(MainActivity main) {
this.main = main;
}
private JSONParser jsonParser = new JSONParser();
String email,password;
EditText emailBox;
EditText passwordBox;
#Override
protected void onPreExecute() {
super.onPreExecute();
TextView textV1 = (TextView)main.findViewById(R.id.textV1);
ProgressBar spinner = (ProgressBar)main.findViewById(R.id.spinner);
spinner.setVisibility(View.VISIBLE);
textV1.setText("Reaching em!!");
}
#Override
protected JSONArray doInBackground(Object... v) {
//main = (MainActivity)parameters[0];
//main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
JSONArray json = null;
json = getUserLoggedIn(email, password);
//main.afterEffect("drawing");
return json;
}
public JSONArray getUserLoggedIn(String email,String password){
JSONArray json = null;
/*
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/testand.php");
*/
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email", email));
pairs.add(new BasicNameValuePair("password", password));
//post.setEntity(new UrlEncodedFormEntity(pairs));
//HttpResponse response = client.execute(post);
//HttpEntity resEntity = response.getEntity();
//if (resEntity != null) {
//String responseStr = EntityUtils.toString(resEntity).trim();
json = jsonParser.getJSONFromUrl("http://117.99.55.83/resource/android/CHATS.php", pairs);
//}
return json;
}
protected void onPostExecute(JSONArray json) {
main.showChatList(json);
}
}
LOGCAT
12-30 17:47:34.418: I/Choreographer(736): Skipped 41 frames! The application may be doing too much work on its main thread.
12-30 17:47:37.221: D/dalvikvm(736): GC_CONCURRENT freed 272K, 13% free 2757K/3168K, paused 77ms+79ms, total 303ms

Categories

Resources