This app is to fetch data from api.github.com/users and reflect on spinner
I am getting data in logs on Splash.java but unable to reflect data on Home.java
MyAppDatabase.java
#Database(entities = {Users.class}, version = 1, exportSchema = false)
public abstract class MyAppDatabase extends RoomDatabase {
public abstract MyDao myDao();
}
MyDao.java
#Dao
public interface MyDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void addUsers(Users users);
#Query("SELECT * FROM Users")
List<Users> getUsers();
#Query("SELECT node_id FROM Users")
List<String> getNodeId();
}
getData() on Splash.java
public class Splash extends AppCompatActivity {
MyAppDatabase myAppDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
myAppDatabase = Room.databaseBuilder(getApplicationContext(), MyAppDatabase.class, "MyDao").allowMainThreadQueries().build();
//get data from webservice and store locally
getData();
}
}, 500);
}
private void getData() {
//Creating a string request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", response.toString());
response.length();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Users users = new Users();
//Set fields in Users object.
users.setLogin(jsonObject.getString(Config.TAG_Login));
users.setId(jsonObject.getString(Config.TAG_Id));
users.setNode_id(jsonObject.getString(Config.TAG_Node));
users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
users.setUrl(jsonObject.getString(Config.TAG_url));
users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
users.setType(jsonObject.getString(Config.TAG_Type));
users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
users.setEvents_url(jsonObject.getString(Config.TAG_events_url));
myAppDatabase.myDao().addUsers(users);
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(Splash.this, Home.class);
// intent.putExtra("remember", "true");
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonArrayRequest);
}
}
putData() on Home.java
public class Home extends AppCompatActivity {
MyAppDatabase myAppDatabase;
//To add into spinner
private ArrayList<String> userType;
//List of users from Db
List<Users> users;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userType = new ArrayList<>();
spinner = findViewById(R.id.sp_user_type);
myAppDatabase = Room.databaseBuilder(getApplicationContext(), MyAppDatabase.class,"UsersDb").allowMainThreadQueries().build();
//get data from Db and put into arrayList for spinner
putData();
}
private void putData() {
users =myAppDatabase.myDao().getUsers();
userType.add("Select UserType"); //Dummy addition
for(int i = 0; i < users.size(); i++){
userType.add(users.get(i).getType());
Log.e("DistNames",users.get(i).getType());
}
users.size();
spinner.setAdapter(new ArrayAdapter<>(Home.this, android.R.layout.simple_spinner_dropdown_item, userType));
}
}
Because you are starting activity in the loop itself, which should be actually outside the loop.
Actually, the mistake that you are doing is it will launch Home activity in the first iteration itself and so you are not getting all the data from the API response. To solve this, let the loop iterates through each entry and add into the database, and start the activity when it completes and so outside the loop.
Wrong:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Users users = new Users();
//Set fields in Users object.
users.setLogin(jsonObject.getString(Config.TAG_Login));
users.setId(jsonObject.getString(Config.TAG_Id));
users.setNode_id(jsonObject.getString(Config.TAG_Node));
users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
users.setUrl(jsonObject.getString(Config.TAG_url));
users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
users.setType(jsonObject.getString(Config.TAG_Type));
users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
users.setEvents_url(jsonObject.getString(Config.TAG_events_url));
myAppDatabase.myDao().addUsers(users);
Intent intent = new Intent(Splash.this, Home.class);
// intent.putExtra("remember", "true");
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
Correct:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Users users = new Users();
//Set fields in Users object.
users.setLogin(jsonObject.getString(Config.TAG_Login));
users.setId(jsonObject.getString(Config.TAG_Id));
users.setNode_id(jsonObject.getString(Config.TAG_Node));
users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
users.setUrl(jsonObject.getString(Config.TAG_url));
users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
users.setType(jsonObject.getString(Config.TAG_Type));
users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
users.setEvents_url(jsonObject.getString(Config.TAG_events_url));
myAppDatabase.myDao().addUsers(users);
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(Splash.this, Home.class);
// intent.putExtra("remember", "true");
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
Related
my code is like this, i don't know why it's getting an empty array even though i added the elements to the array during request.
public class MainActivity extends AppCompatActivity {
private List<Question> questionList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionList = new QuestionBank().getQuestions();
Log.d("Main", "processFinished: " + questionList);
}
// the request
public class QuestionBank {
ArrayList<Question> questionArrayList = new ArrayList<>();
private String url = "https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json";
public List<Question> getQuestions() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
Question question = new Question();
question.setAnswer(response.getJSONArray(i).get(0).toString());
question.setAnswerTrue(response.getJSONArray(i).getBoolean(1));
questionArrayList.add(question);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
return questionArrayList;
}
}
// Log result
D/Main: processFinished: []
You can pass a callback as following ways
step 1:
Create an Intercafe
public interface TestCallBack {
void callBack(List<Question> response) ;
}
Step 2:
create anonymous objects
TestCallBack testCallBack=new TestCallBack() {
#Override
public void callBack(List<Question> response) {
// here you will get a response after success
}
};
and pass this reference to
questionList = new QuestionBank().getQuestions(testCallBack);
Log.d("Main", "processFinished: " + questionList);
Step 3:
call this method from after the response from the server
public List<Question> getQuestions(TestCallBack testCallBack) {
public void onResponse(JSONArray response) {
testCallBack.callBack(questionArrayList); // pass your array list here
}
}
It is empty because you are populating it asynchronously. you should add a callback as a parameter, call it in onResponse.
Please help me to fix this code , i"m a new programmer and start learn java at android studio. here the code . i have fixed it but not complate . so many problem
private void request()
{
Log.d("VOLLE------","MAUKKKK");
JsonArrayRequest requestItem = new JsonArrayRequest(Request.Method.POST, url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject data = response.getJSONObject(i);
OurData item = new OurData();
item.setId(data.getString("idperawatan"));
item.setmText1(data.getString("nama"));
item.setmText2(data.getString("alamat"));
item.setmImageResource(data.getString("image"));
mList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(requestItem);
}
Looks like it's complaining about mismatched arguments in JsonArrayRequest(). Try removing the POST method and JSONArray arguments and pass the url String as the first parameter:
private void request() {
Log.d("VOLLE------","MAUKKKK");
JsonArrayRequest requestItem = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject data = response.getJSONObject(i);
OurData item = new OurData();
item.setId(data.getString("idperawatan"));
item.setmText1(data.getString("nama"));
item.setmText2(data.getString("alamat"));
item.setmImageResource(data.getString("image"));
mList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(requestItem);
}
Hey i'm creating Android application which connect with my database MySQL. I created an ArrayList with categories and added it to Adapter and then to Spinner. I see Spinner items but after onClick nothing happens and when I try to check what is in my ArrayList I see that it is empty.Data downloaded.
After click in Spinner nothing change
Here is my code:
public class InsertProductActivity extends AppCompatActivity {
Spinner categories;
String categoriesURL = "myURL";
ArrayList<String> downloadedCategories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_product);
categories = findViewById(R.id.categories);
getCategories();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
}
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
for(int i=0;i<jsonArray.length();i++){
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
}
try this one.
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
downloadedCategories = new ArrayList<>(); // try to add your instantiation of your arrayList here.
for(int i=0;i<jsonArray.length();i++) {
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//this block of code will prompt after your downloadedCategories finish storing your objects to your arrayList because if you put this in onCreate this wil call before your getCategories process not finish yet. So much better its much safer here.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
requestQueue.add(jsonObjectRequest);
}
I want to move GET method inside (if) that located inside onResponse of POST request without calling URL again because once the user post edittext php file will echo json result that will show up inside listview in activity so if call URL again in other method nothing will show up, how can I do that please?
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aalm/getticket.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("responseticket")) {
showTicket();
} else {
Toast.makeText(supportActivity.this, "Check the number please", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
RequestQueue requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
private void showTicket(){
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("responseticket");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject ticket = jsonArray.getJSONObject(i);
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "Volley");
}
}
);
requestQueue2.add(jsonObjectRequest);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}
I am trying to display a ProgressDialog while my app is getting data from a web service. I also would like to call a method in MapsActivity (main activity) when DataController is done adding objects from parsing web service.
In my code nothing happens (i.e. no ProgressDialog appears) and I'm stuck on how to let MapsActivity know that the objects have been created.
As you can see I've tried to make the ProgressDialog appear with
pd.show(context, "text", "text")
MapsActivity.java
public class MapsActivity extends FragmentActivity {
private DataController controller = new DataController(MapsActivity.this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
sharedPref = new SharedPreference(MapsActivity.this);
storedLikes = controller.readLike(sharedPref);
//This runs getLikedPos() in DataController
/Lots of code....
DataController.Java
public class DataController {
// Fields
public DataController(MapsActivity mapsActivity) {
this.context = mapsActivity;
}
public void getLikedPos() {
this.url = getUrl();
JsonObjectRequest jrequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
ProgressDialog pd = ProgressDialog.show(context, "In progress", "Loading");
int success = response.getInt("success");
if (success == 1) {
JSONArray ja = response.getJSONArray("spots");
for (int i=0; i < ja.length(); i++) {
JSONObject spot = ja.getJSONObject(i);
Location location = new Location("");
location.setLatitude(spot.getDouble(LIKE_LAT));
location.setLongitude(spot.getDouble(LIKE_LONG));
int id = spot.getInt(LIKE_ID);
String time = spot.getString(LIKE_TIMESTAMP);
Calendar parsedTime = convertDate(time);
likeArr.add(new Like(location, id, parsedTime));
}
System.out.println("Size of LikeArr ArrayList after parsing: " + likeArr.size());
pd.dismiss();
//context.updateMap(); ??
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});