Arraylist is showing empty while json parsing in android - java

I am a novice in android. I am learning data parsing, using Json. I am storing data to a arraylist. The problem is, sometime the arraylist shows all the data and most of the times it seems empty. I set a toast message for all iterator and in toast message all data are showing always, in fact while list is showing empty, toast is showing data, It means data parsing is alright, problem is occurring at the time of adding them into list. Why I am not getting the data in the list all the time and how can I get rid of it.Thanks in advance.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list);
list = new ArrayList<String>();
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
RequestQueue requestQueue = VolleySingleTon.getInstance().getRequestQueue();
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET
, url
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// list = worksonresponse(response);
try {
JSONArray arraymovie = response.getJSONArray("movies");
for (int i = 0; i < 20; i++) {
JSONObject currentmovie = arraymovie.getJSONObject(i);
// String name = currentmovie.getString("title");
list.add(arraymovie.getJSONObject(i).getString("title"));
makeToast(arraymovie.getJSONObject(i).getString("title"));
lv.setAdapter(adapter);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
makeerror(error);
}
});
requestQueue.add(objectRequest);
// requestQueue.add(stringRequest);
//adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
// lv.setAdapter(adapter);
if (list == null || list.size() == 0) {
Log.e("about list", "list is empty");
} else {
Log.e("about list", "size is =" + list.size());
}
}

Put this line
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
right after this line:
list = new ArrayList<String
and add
adapter.notifyDatasetChanged()
after your for loop

Related

Android JsonArrayRequest onResponse is never executed

this issue has been bugging me all day. I have stepped through the program with the debugger and it never goes into the Response.Listener. It doesn't go into onErrorResponse either so the API isn't throwing an error.
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_rewards);
prf = new PrefManager(this);
getSupportActionBar().setIcon(R.drawable.ic_back_icon);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.earning_history);
listView = (ListView) findViewById(R.id.list);
TextView emptyText = (TextView) findViewById(R.id.empty);
emptyText.setText(getString(R.string.no_rewards_yet));
adapter = new UserHistoryAdapter(EarningHistoryActivity.this, historyList);
listView.setAdapter(adapter);
listView.setEmptyView(emptyText);
listView.setDivider(null);
pDialog = new ProgressDialog(this);
pDialog.setMessage(getString(R.string.loading));
pDialog.show();
// changing action bar color
// getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1b1b1b")));
JsonArrayRequest historyReq = new JsonArrayRequest(Config.Base_Url+"api/earning_history.php?username="+App.getInstance().getUsername(), new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
UserHistory history = new UserHistory();
history.setTitle(obj.getString("type"));
history.setRating(obj.getString("date"));
history.setThumbnailUrl(Config.Base_Url+"images/reward.png");
history.setYear(obj.getString("points"));
//history.setGenre(obj.getString("time"));
historyList.add(history);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(historyReq);
}
Any help would be greatly appreciated.
Edit: I added more code from the entire onCreate method to give some more information to help.
You have created historyReq object of class JsonArrayRequest;
Now there should be some method call inside JsonArrayRequest class which make utilize the Response.ErrorListener() object that you injected inside the historyReq. The injected objected inside historyReq should make use of on onErrorResponse method.
For more info you can see behavior of Anonymous class.

No adapter attached; skipping layout - beginner issue

Im using volley to download the JSON data from a server, setting the Adapter within the function that reads and parses the data. However, the adapter is not being recognized. The problem is, I have successfully implemented the adapter in another activity with the same method without errors. The following is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras!=null) {
user_id = getIntent().getStringExtra("user_id");
} else {
Intent logIn = new Intent(JoinedActivity.this, LoginActivity.class);
startActivity(logIn);
}
setContentView(R.layout.activity_joined);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
GetJoinedEvents();
}
public void GetJoinedEvents(){
String tag_string_req = "req_getJoinedEvents";
StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.URL_USER_lIST_EVENTS+user_id, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
// progressDialog.dismiss();
Log.i("responseTest",response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
int length = result.length();
HashMap<String, String> events;
for (int i = 0; i < length; i++) {
JSONObject jo = result.getJSONObject(i);
String event_id = jo.getString(Config.TAG_EVENT_ID);
String name = jo.getString(Config.TAG_EVENT_NAME);
String date = jo.getString(Config.TAG_EVENT_START_DT);
String weekday = jo.getString(Config.TAG_EVENT_WEEKDAY);
String event_type = jo.getString(Config.TAG_EVENT_TYPE);
events = new HashMap<>();
events.put(Config.TAG_EVENT_ID, event_id);
events.put(Config.TAG_EVENT_NAME, name);
events.put(Config.TAG_EVENT_START_DT, date);
events.put(Config.TAG_EVENT_WEEKDAY, weekday);
events.put(Config.TAG_EVENT_TYPE, event_type);
eventList.add(events);
}
listAdapter = new RecyclerViewAdapter(JoinedActivity.this,eventList, user_id);
recyclerView.setAdapter(listAdapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Bad internet connection");
}
}) {};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
Log.i("URL", stringRequest.toString());
}
}
A better approach to this is just to initialize the Recycler view and adapter on the onCreate. Then later on when you have the data you could create a swapItems method just for the purpose of changing the data within the recyclerview through the adapter, but in a way that both the RecyclerView and its adapter is instantiated as the activity starts.
on your swapItems you could do something like below:
public void swapItems(List<Events> eventList) {
if (eventList != null) {
this.items = eventList;
notifyDataSetChanged();// should call this to let the recyclerview know that our data set has changed
}
}
Then you could just call it via the activity by
listAdapter.swapItems(eventList);// this is done the moment you already got your list of events

Parsing simple json to spinner entries

I've been trying to get into android/java programming and I've been having issues understanding how to properly get the value of this json and parse it into the options to select in a spinner.
My json is like:
["Result1","Result2","Result3"]
My current code is like:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://example.com/jsonfile.json";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.toString());
}
});
queue.add(stringRequest);
}
What would be the easiest way to get these values (Result1, Result2, Result3, etc.) into the spinner.entries?
Thanks in advance
Try this:
myString.replace("\"]","");
myString.replace("[\"","");
List<String> myList = new ArrayList<String>(Arrays.asList(s.split("\",\"")));
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myList);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
As per my knowledge you are sending json data in the wrong way.
If you want to send an array you have to place a jsonArray object in response with name to access that jsonArray.
Example
"cars":[ "Ford", "BMW", "Fiat" ]
Here, we are sending 3 car name in JsonArray of name "cars".
For accessing those entries:-
for (i in myObj.cars) {
carsArray += myObj.cars[i];
}
You need to make an assync call to get json data. Please refer the following tutorial
Android assync task example
and for parsing json data use Android json parsing example
#Override
public void onResponse(String response) {
//Do something with response
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
array.put(jsonArray.getString(i));
}
}
add this on your activity's OnCreate() metod
ArrayAdapter<CharSequence> adapter =
ArrayAdapter.createFromResource(this, array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
and put it
ArrayList<String> array = new ArrayList<String>();
Hello Try this if it may help
public class MainActivity extends AppCompatActivity {
Button btnCall;
final List<String> reviewList = new ArrayList<>();
List<String>resultList=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCall=(Button)findViewById(R.id.btnCall);
final String jArrStr="[\"Result1\",\"Result2\",\"Result3\"]";
btnCall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
JSONArray jArry=new JSONArray(jArrStr);
for (int i = 0; i < jArry.length(); i++) {
String strArr=jArry.getString(0);
resultList.add(jArry.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}

JSONArray to a ListView array data not shown

i want to when run the app make the jsonRequest without pressing any button and save the data. i just add a method for internet connection check:
if the connection to the internet its true, make the json request pass to the spinner, and save de data.
and when the internet connection its false, just load the data from sharedPreferences to the spinner.
The application runs totally fine with the buttons (with simple onClick methods) and without the verificaConexion method.
But when i remove the buttons, add the verificaConexion method and i have internet connection, just, make the json request, show the data in the spinner and not save the data And when I close the app, remove the wifi, open the app, the spinner shows nothing.
For any reason the methods save and load data doesn't works.
This is my onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnObtener = (Button) findViewById(R.id.btnObtener);
spDelegaciones = (Spinner)findViewById(R.id.spDelegaciones);
btnGuardar = (Button) findViewById(R.id.btnGuardar);
btnCargar = (Button) findViewById(R.id.btnCargar);
txJsonArray = (TextView) findViewById(R.id.txJsonArray);
verificaConexion(this);
}
This is my json Request method, works fine:
public void request() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(json_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("jsonArray", "" + jsonArray);
if (jsonArray == null) {
Toast.makeText(MainActivity.this, "EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//con el php JsonArrayRequest2.php
// String contact = jsonObject.getString("delegacion");
//con el php JsonArrayVariosCampos.php
String contact = jsonObject.getString("Delegacion");
arrayList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "ERROR...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonArrayRequest);
}
my guardarDatos method to save the data:
public boolean guardarDatos(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
/* sKey is an array */
mEdit1.putInt("Status_size", arrayList.size());
for(int i=0;i<arrayList.size();i++)
{
mEdit1.remove("Status_" + i);
mEdit1.putString("Status_" + i, arrayList.get(i));
}
Toast.makeText(MainActivity.this, " DATOS GUARDADOS ", Toast.LENGTH_SHORT).show();
return mEdit1.commit();
}
and my cargarDatos method to load the data:
public void cargarDatos(){
SharedPreferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
arrayList.clear();
int size = mSharedPreference1.getInt("Status_size", 0);
for(int i=0;i<size;i++)
{
arrayList.add(mSharedPreference1.getString("Status_" + i, null));
}
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
spDelegaciones.setAdapter(adapter);
Toast.makeText(MainActivity.this, " DATOS CARGADOS ", Toast.LENGTH_SHORT).show();
}
and here is my class to check the internet connection:
public boolean verificaConexion(Context ctx){
boolean bConectado = false;
ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] redes = connec.getAllNetworkInfo();
for (int i = 0; i < 2; i++) {
if (redes[i].getState() == NetworkInfo.State.CONNECTED) {
bConectado = true;
if(bConectado) {
Toast.makeText(MainActivity.this, " con conexion ", Toast.LENGTH_LONG).show();
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
spDelegaciones.setAdapter(adapter);
request();
guardarDatos();
}else {
cargarDatos();
}
}else{
}
}
return bConectado;
}
Since you are using only one string in contact class. instead of arrayList<Contact> I will use ArrayList<String>
here I have removed singleTone class. and added jsonArrayRequest code inside in same class. and after adding item in arraylist I have called adapter.notifyDataSetChanged();
MainActivity.class
public class MainActivity extends AppCompatActivity {
TextView txdeleg_lista;
Button btnObtener;
ArrayList<String> arrayList = new ArrayList<String>();
ListView listView;
String json_url = "your url";
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnObtener = (Button) findViewById(R.id.btnObtener);
txdeleg_lista = (TextView) findViewById(R.id.txdeleg_lista);
listView = (ListView) findViewById(R.id.lvDelegacion);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
btnObtener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//startActivity(new Intent(MainActivity.this, DesplegarLista.class));
listView.setAdapter(adapter);
request();
}
});
}
public void request() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(json_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("jsonArray",""+jsonArray);
if(jsonArray == null){
Toast.makeText(MainActivity.this,"EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
}
else {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact = jsonObject.getString("UFULLNAME");
arrayList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"ERROR...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonArrayRequest);
}
}
check and if you have any query comment.

Parsing RSS on Android

I've got a couple RSS feeds I need to parse for my app and I followed the excellent tutorial here: http://w2davids.wordpress.com/android-rssatom-feeds-parsing-with-rome/. I modified the sample a bit and got it to do what I needed. So, I went to integrate it into my app and consistently get a Force Quit every time I try to display the list of posts. My modified version of the code is below. It always seems to fail when attaching the adapter to the ListView, so I assume my adapter is setup incorrectly. What's strange us that in the debugger, I can look at the adapter and see the data I'm trying to fetch.
Thanks in advance:
public class View1 extends Activity
{
/** Called when the activity is first created. */
private final ArrayList<String> list = new ArrayList<String>();
private ListView listView;
private ArrayAdapter<String> adapter = null;
private SyndContent desc;
private ArrayList<String> d = new ArrayList<String>() ;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter = new ArrayAdapter<String>(this, R.layout.dataview, R.id.ListItemView);
getRSS("http://www.example.com/wp/?feed=gigpress&artist=1");
listView.setAdapter(adapter);
listView = (ListView) this.findViewById(R.id.ListView);
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long duration)
{
Intent intent = new Intent();
intent.setClassName("com.example.idtb", "com.example.idtb.ViewRssDescription");
intent.putExtra("desc", d.get(position));
startActivity(intent);
}
});
}
private void getRSS(String rss)
{
URL feedUrl;
try
{
Log.d("DEBUG", "Entered:" + rss);
feedUrl = new URL(rss);
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));
List entries = feed.getEntries();
Iterator iterator = entries.listIterator();
while (iterator.hasNext())
{
SyndEntry ent = (SyndEntry) iterator.next();
String title = ent.getTitle();
desc = ent.getDescription();
d.add(desc.getValue());
adapter.add(title);
}
adapter.notifyDataSetChanged();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (FeedException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I think adapter should look something like this:
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lst);

Categories