Im getting this error while trying to get data from JSON - java

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");
....

Related

Problem to implement API in Android Studio

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

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`
}
}

Catch a Json string (made using dot net , newtonsoft) in android using Volley.

I need to catch a json string (in my case: ["Java","C","C++"]) in android app using Volley and put it inside a String array courseList.
A few closing brackets may be missing, sorry for that, there is more code in my file, but i could not copy it whole.Please provide code if u can, it will b really helpful. Thanks)
Here is my attempted code:
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
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.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
ListView simpleList;
final String[] courseList = new String[3];// = {"HR","C Programming", "C++","C#", "Java", "Javascript", "Angular JS", "Data Structure", "Ajax", "Asp.Net", "jQuery", "json", "SQL"};
int flags[] = {R.drawable.hr,R.drawable.cprogramming, R.drawable.cplus, R.drawable.csharp, R.drawable.java, R.drawable.javascript, R.drawable.angularjs, R.drawable.datastructures, R.drawable.ajax, R.drawable.aspnet, R.drawable.jquery, R.drawable.json, R.drawable.sql};
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for volley
String jsonURL = "http://192.168.0.131:10462/WebService1.asmx";
final String data = "";
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
JSONObject jsonRequest = new JSONObject();
try {
jsonRequest.put("GetTopic",Request.Method.GET );
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonURL,jsonRequest,
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("GetTopic");
// Retrieves the string labeled "colorName" and "description" from
//the response JSON Object
//and converts them into javascript objects
String color = obj.getString("GetTopic");
// Adds strings from object to the "data" string
String data = "Topic Name: " + color ;
// Adds the data string to the TextView "results"
// results.setText(data);
courseList[0] = data;
courseList[1] = data;
courseList[2] = data;
// Toast.makeText(getApplicationContext(),data,Toast.LENGTH_LONG).show();
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
});
requestQueue.add(jsonObjectRequest);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), courseList, flags);
}

Json parse work on inner class but doesn't work on separate class

I want to display JSON data in textView and i do that but the problem is when i create a separate class for lood JSON data and Store into A ArrayList, it doesn"t work.
Here is my code please help me what i can do to solve that problem.
My inner class code
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.mdashikurrahman.transactions.AppController;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeJsonArrayRequest();
}
});
}
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
Separate class code
BackgroundTask
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by MD ASHIKUR RAHMAN on 9/24/2016.
*/
public class BackgroundTask {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
/**
* Method that return a arraylist which made by jsonArray
* */
public ArrayList<HouseOrPerson> makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
return arrayList;
}
}
InsertActivity class where i create a object ob BackGround class and call makeJsonArrayRequest method
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.mdashikurrahman.transactions.BackgroundTask;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask bg = new BackgroundTask();
arrayList=bg.makeJsonArrayRequest();
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
}
});
}
}
Arent you missing a constructor in your BackgroundTask?
Try putting System.out.println(arrayList.size()) before you return it in your BackgroundTask. What is the size of it?

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