No adapter attached; skipping layout - beginner issue - java

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

Related

Getting data from webservice android studio

I am working on an android application. In this application, I have to retrieve data from a web service and put it in a listview, but it is not retrieving anything. I don't know what I am doing wrong here. Maybe someone can help me with this.
Webservice: http://10.247.240.53/kas/lampen.php
Mainactivity:
`
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listview);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
getData();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Showdata.class);
intent.putExtra("teeltbed", listView.getItemAtPosition(position).toString());
startActivity(intent);
}
});
}
private void getData()
{
String getData = null;
String dbResult = "empty";
dbConnect database = new dbConnect(this);
try{
String query = "SELECT * FROM Lamp";
getData = "?query=" + URLEncoder.encode(query, "UTF-8");
String link = "http://10.247.240.53/kas/lampen.php";
dbResult = database.execute(link).get();
}
catch (Exception e){
}
try{
JSONArray ja = new JSONArray(dbResult);
JSONObject jo = null;
data = new String[ja.length()];
for (int i = 0; i < ja.length(); i++)
{
jo = ja.getJSONObject(i);
data[i] = jo.getString("teeltbed");
}
adapter = new ArrayAdapter<String>(this, R.layout.layout_list, R.id.list_item, data);
listView.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}`

Adapter.notifyDataSetChanged() not working inside onCreate()

I am trying to parse JSON using Volley.
I am using a vector to store parsed data and calling adapter.notifyDataSetChanged() inside onCreate() after filling vector. But no changes are there.
If I am calling adapter.notifyDataSetChanged() inside try-catch block of getData() then it is working fine. Why?
public class MainActivity extends AppCompatActivity{
Vector<Data> ve;
private Adapter adapter;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=(RecyclerView)findViewById(R.id.main_recycler_view);
ve=new Vector<Data>();
adapter=new Adapter(ve);
RecyclerView.LayoutManager lm=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(lm);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
getData(ve);
adapter.notifyDataSetChanged(); //not working
}
public void getData(final Vector<Data> ve)
{
String url = "https://api.androidhive.info/contacts/";
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String jsonString) {
try
{
JSONObject object = new JSONObject(jsonString);
JSONArray arr = object.getJSONArray("contacts");
int len=arr.length();
JSONObject obj;
for (int i = 0; i < len; i++)
{
obj = arr.getJSONObject(i);
ve.add(new Data(obj.getString("name"), obj.getString("email"));
}
//adapter.notifyDataSetChanged();working
}
catch (JSONException e)
{
Toast.makeText(getApplicationContext(),"JSON Parsing Exception",Toast.LENGTH_LONG);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
}
});
RequestQueue rQueue = Volley.newRequestQueue(this);
rQueue.add(request);
}
}
you cannot do that reason nothing volley used network requests which are designed to be asynchronous in nature , so the network request is put in queue and code continues to execute the notifyadapter changed method . The response to the network call occurs afterwards and add data, you should call that method after data is received by calling it inside volley on response method

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.

Arraylist is showing empty while json parsing in android

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

Categories