Android JSON Data not Displayed in ListView ( Using Realm ) - android

im trying to get data from a server inform of JSON and im storing the data to my offline database ( in this case : Realm ), whenever i try to retrieve the data, nothing is displayed in the listview.
public class MainActivity extends AppCompatActivity {
public static ListView myList;
public static ListAdapter myAdapter;
public static Realm realm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Realm.init(this);
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Recipe> dRecipies = realm.where(Recipe.class).findAll();
if(dRecipies!= null)dRecipies.deleteAllFromRealm();
}
});
DownloadTask newTask = new DownloadTask();
newTask.execute("hi");
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.Recipe_list);
// getData();
setDisplay();
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String p = String.valueOf(position);
Intent in = new Intent(MainActivity.this, SecondScreenDetails.class);
in.putExtra("Position", p);
startActivity(in);
}
});
}
public void setDisplay(){
ArrayList<Recipe> finalRecipies = new ArrayList<>();
RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();
for(Recipe r: rrRecipies){
finalRecipies.add(r);
Toast.makeText(this, r.getName(), Toast.LENGTH_SHORT).show();
}
myAdapter = new ListViewAdapter(this, finalRecipies);
myList.setAdapter(myAdapter);
}
#Override
protected void onDestroy() {
realm.close();
super.onDestroy();
}
}
im doing this because, if i dont, the data keeps getting repeatedly stored, resulting in repetition.
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Recipe> dRecipies = realm.where(Recipe.class).findAll();
if(dRecipies!= null)dRecipies.deleteAllFromRealm();
}
});
when i tried without actually deleting the data, then the Toast in the
setDisplay() method is working and the data is being shown.(Toasts are repeated as i open the app second time, it gets twice... etc)
When i insert this, even the toasts dont show up.
My download activity
public class DownloadTask extends AsyncTask<String,Void,String> {
private RealmList<Recipe> realmRecipe = new RealmList<>();
String result;
#Override
protected String doInBackground(String... params) {
result = "";
Realm realm = null;
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json").build();
try {
result = client.newCall(request).execute().body().string();
Log.i("RESULT", result);
JSONArray rootArray = new JSONArray(result);
for (int i = 0; i < rootArray.length(); i++) {
JSONObject tempObject = rootArray.getJSONObject(i);
JSONArray jIngredients = tempObject.getJSONArray("ingredients");
JSONArray jSteps = tempObject.getJSONArray("steps");
// Get the ingredients
List<Ingredients> ingredients = new ArrayList<>();
for (int j = 0; j < jIngredients.length(); j++) {
JSONObject tempIngredient = jIngredients.getJSONObject(j);
Ingredients nIngredient = realm.createObject(Ingredients.class);
nIngredient.setIngredient(tempIngredient.getString("ingredient"));
nIngredient.setMeasure(tempIngredient.getString("measure"));
nIngredient.setQuantity(tempIngredient.getString("quantity"));
// Ingredients newIngredient = new Ingredients(tempIngredient.getString("quantity"),
// tempIngredient.getString("measure"),
// tempIngredient.getString("ingredient"));
// ingredients.add(newIngredient);
ingredients.add(nIngredient);
}
// Get the steps
List<Steps> steps = new ArrayList<>();
for (int j = 0; j < jSteps.length(); j++) {
JSONObject tempStep = jSteps.getJSONObject(j);
Steps nStep = realm.createObject(Steps.class);
nStep.setDescription(tempStep.getString("description"));
nStep.setId(tempStep.getString("id"));
nStep.setShortDescription(tempStep.getString("shortDescription"));
nStep.setVideoURL(tempStep.getString("videoURL"));
steps.add(nStep);
// Steps newStep = new Steps(tempStep.getString("id"), tempStep.getString("shortDescription"),
// tempStep.getString("description"), tempStep.getString("videoURL"));
// steps.add(newStep);
}
// Create the recipe
Recipe nRecipe = realm.createObject(Recipe.class);
nRecipe.setId(tempObject.getString("id"));
nRecipe.setName(tempObject.getString("name"));
nRecipe.setServings(tempObject.getString("servings"));
nRecipe.setIngredients(ingredients);
nRecipe.setSteps(steps);
realmRecipe.add(nRecipe);
// Recipe newRecipe = new Recipe(tempObject.getString("id"), tempObject.getString("name"), tempObject.getString("servings"), ingredients, steps);
// MainActivity.mRecipies.add(newRecipe);
}
}catch (Exception e){
Log.i("Error Message", e.getMessage());
}
}
});
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}

Related

sorting a ListView by number

sort ListView Android by float number ...
I have a listview price type float display of a mysql database ,,
I want to sort it (by order) but I have not found a solution ..
how can I do it please !!!
it's the code of my listView with prices done !!
private class GetHttpResponse extends AsyncTask<Void, Void, Void>{
public Context context;
String ResultHolder;
List<subjects> subjectsList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpServicesClass httpServiceObject = new
HttpServicesClass(ServerURL);
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
subjects subjects;
subjectsList = new ArrayList<subjects>();
for(int i=0; i<jsonArray.length(); i++)
{ subjects = new subjects();
jsonObject = jsonArray.getJSONObject(i);
subjects.SubjectName = jsonObject.getString("tarif");
subjectsList.add(subjects);
} }
catch (JSONException e) {
e.printStackTrace();
} } } else
{
Toast.makeText(context, httpServiceObject.getErrorMessage(),
Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{ progressBarSubject.setVisibility(View.GONE);
SubjectListView.setVisibility(View.VISIBLE);
if(subjectsList != null)
{
ListAdapterClass adapter = new ListAdapterClass(subjectsList,
context);
SubjectListView.setAdapter(adapter);
SubjectListView.setOnItemClickListener(new
AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int pos, long id) {
String selectedItem =
parent.getItemAtPosition(pos).toString();
Toast.makeText(TechnicienActivity.this,selectedItem,
Toast.LENGTH_SHORT).show();
Intent intent = new
Intent(getApplicationContext(),Main2Activity.class);
intent.putExtra("Position" , String.valueOf(id));
startActivity(intent);
} }); } } }
You can sort the list by using
Collections.sort(list);
and then set this to the listview.
Example;
subjectsList.add(subjects);
Collections.sort(subjectsList);

How to display name in spinner dynamically from server

Hi Now I'm retrieving data to spinner dynamically, but now it displaying some id's but those Id details are stored in other table, I want display those details in the spinner instead of id. And if I select particular product in spinner according that product details should display in list.
I'm using Retrofit method for retrieving data from server
package cfirst.live.com.activity;
public class Pos_outlet extends AppCompatActivity implements RestCallback,View.OnClickListener{
Spinner spinner;
ArrayList<String> products;
String numberAsString, product_name;
int i;
private int cartProductNumber = 0;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pos_outlet);
sharedPreference = new MySharedPreference(Pos_outlet.this);
GsonBuilder builder = new GsonBuilder();
gson = builder.create();
initViews();
}
private void initViews() {
row1 =(TableRow)findViewById(R.id.row1);
spinner=(Spinner)findViewById(R.id.spinner);
POSStoreID = (TextView) findViewById(R.id.POSStoreID);
POSLocationID = (TextView) findViewById(R.id.POSLocationID);
Intent intent = getIntent();
id = intent.getStringExtra("id");
index_id= intent.getStringExtra("index_id");
callStoreDetaislsAPI();
callSmbProductsAPI();
getProductAPI();
}
// **Using this api I'm setting id'd to spinner**
private void getProductAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("store", index_id);
Toast.makeText(getApplicationContext(),index_id, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getproductlist(map, new MyCallback<List<PosmultistoresModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Finding products....", GlobalVariables.SERVICE_MODE.GET_PRODUCTS));
}
// **this API have product Id's Details**
private void callSmbProductsAPI() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("index_id", product);
//Toast.makeText(getApplicationContext(),added_by, Toast.LENGTH_LONG).show();
RestService.getInstance(Pos_outlet.this).getSmbProduct(map, new MyCallback<List<PosSmbProductModel>>(Pos_outlet.this,
Pos_outlet.this, true, "Fetching details....", GlobalVariables.SERVICE_MODE.SMB_PRODUCT));
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.AddtoBasket:
callPosProductsAPI();
callSmbProductsAPI();
break;
}
}
#Override
public void onFailure(Call call, Throwable t, GlobalVariables.SERVICE_MODE mode) {
//Toast.makeText(getApplication(),"failure",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(Response response, GlobalVariables.SERVICE_MODE mode) {
switch (mode) {
//** I'm setting data to spinner **
case GET_PRODUCTS:
try {
List<PosmultistoresModel> businessgroups = (List<PosmultistoresModel>) response.body();
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
ArrayAdapter<String> adapter1;
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, items);
//setting adapter to spinner
spinner.setAdapter(adapter1);
} catch (Exception e) {
e.printStackTrace();
}
break;**
// ** Product id details (title, image, etc) Api
case SMB_PRODUCT:
try {
ArrayList<PosSmbProductModel> products = (ArrayList<PosSmbProductModel>) response.body();
//Product_id = products.get(0).getProduct();
// for (int i = 0; i < products(); i++) {
Title = products.get(0).getTitle();
productname1.setText(Title);
imageid12 = products.get(0).getMain_image();
Picasso.with(this).load("https://www.consumer1st.in/pre_production/uploads/" + imageid12).into(imageid1);
}
// }
catch(Exception e)
{
e.printStackTrace();
}
break;
}
}
}
I am assuming that your product_name = businessgroups.get(0).getProduct(); is getting a pruduct.
First of all please remove this part
product_name = businessgroups.get(0).getProduct();
List<PosmultistoresModel> list=null;
for(i=0;i<businessgroups.size();i++)
{
list=businessgroups;
}
items = new String[list.size()];
for(int i=0; i<businessgroups.size(); i++){
//Storing names to string array
items[i] = list.get(i).getProduct();
}
then can you try
ArrayList<String> productList = new ArrayList<>();
for (int i = 0; i < businessgroups.size(); i++) {
productList.add(businessgroups.get(i).getProduct());
}
And finally
adapter1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, productList);

Store all the information at once using Realm in Background thread Android

I am developing an android app, where I am using Relam as local Database. I have rest api one for all the user information and other is for news information. I have two buttons. one for showing the user information and other is for showing the news information. Now, with my code what is done, after login, I need to click the button at first for user information and news information accordingly and then I can see those images and news. but if I connection off, just after login, the data is not showing in the view. I am explaining my code in detail.Also I am having problem in image loading. How can I Make the funtionality so that user can get all the information just after login.I am reallly sorry for such a long code. It would be really helpful for me if someone tell me how can I modify my code to store all data in background thread, so that user get all information just after login.
The part of the login page where I want to start
private void loginUser(final String mEmail, final String mPassword) {
final GlobalClass globalClass = new GlobalClass();
globalClass.setEmail_info( mEmail );
setFilePath();
RequestQueue queue = Volley.newRequestQueue( LoginPage.this );
StringRequest strReq = new StringRequest( Request.Method.POST,
LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d( TAG, "Register Response: " + response.toString() );
//parse your response here
if (response.contains( "overview" )) {
showProgress( true );
globalClass.setImage_urlpath( Constants.HTTP.PHOTO_URL + mEmail);
String str = globalClass.readDatafromStorage();
Log.d("----After Login---",str);
if ( !str.contains("ACTIVATE") ) {
Log.d( "----After Login---", "After Login" );
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(KEY_EMAIL, mEmail);
editor.putString(KEY_PASSWORD, mPassword);
editor.commit();
showProgress(false);
Intent loginIntent = new Intent(LoginPage.this, MainOptionPage.class);
loginIntent.putExtra(KEY_EMAIL, mEmail);
startActivity(loginIntent);
} else {
userEmail.setError(getString(R.string.error_incorrect_login));
userEmail.requestFocus();
}
}
}, new Response.ErrorListener() {
#Override
....
Here is my code for User Page
public class MyColleaguesPage extends AppCompatActivity implements ColleagueController.UserCallbackListener {
private List<MyColleagueModel> myColleagueList = new ArrayList<>();
private Realm colleagueRealm;
private RealmResults<MyColleagueModel> colleagueResult;
private List<MyColleagueModel> filteredModelList;
private RealmChangeListener realmListener;
private static final String DIALOG_TAG = "EmployeeDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mycolleagues_layout);
configViews();
}
private void configViews() {
recyclerView = this.findViewById(R.id.colleagues_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(MyColleaguesPage.this));
recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
colleagueRealm = Realm.getDefaultInstance();
RealmResults<MyColleagueModel> results = colleagueRealm.where(MyColleagueModel.class).findAll();
for (int i = 0; i < results.size(); i++) {
myColleagueList.add(results.get(i));
}
adapter = new MyColleaguesAdapter(myColleagueList,getApplicationContext());
//adapter = new MyColleaguesAdapter(myColleagueList,getApplicationContext());
Log.d( "adapter value is"+"", String.valueOf( adapter ) );
recyclerView.setAdapter(adapter);
}
//successful
#Override
public void onFetchStart() {
}
#Override
public void onFetchProgress(ColleagueModel colleague) {
//adapter.addColleague(colleague);
}
#Override
public void onFetchProgress(List<ColleagueModel> colleagueList) {
}
#Override
public void onFetchComplete() {
}
#Override
public void onFetchFailed() {
}
}
Here is my controller class for my colleague page
public class ColleagueController {
private static final String TAG = ColleagueController.class.getSimpleName();
private UserCallbackListener mListener;
private ColleagueResApiManager mApiManager;
Realm myColleague_realm;
public ColleagueController() {
mApiManager = new ColleagueResApiManager();
}
public void startFetching(){
myColleague_realm = Realm.getDefaultInstance();
mApiManager.getColleagueApi().getColleague(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for(int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
Log.d("-----Start Fetching---", object.optString( "name" ));
myColleague_realm.beginTransaction();
MyColleagueModel mycolleague = myColleague_realm.createObject( MyColleagueModel.class );
mycolleague.setName( object.optString( "name" ) );
.... data ) );
myColleague_realm.commitTransaction();
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
// mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
if (mListener != null) {
mListener.onFetchComplete();
}
}
});
}
public interface UserCallbackListener{
void onFetchComplete();
void onFetchFailed();
}
}
In the same way I have other page news option page where I am shoing the news data. Here is my news page.
public class NewsPage extends AppCompatActivity{
private RecyclerView recyclerView;
private NewsAdapter adapter;
private Realm newsRealm;
private List<NewsRealmModel> mNewsList;
private List<NewsRealmModel> filteredModelList;
private NewsController mController;
Constant constant;
SharedPreferences app_preferences;
int appTheme;
int themeColor;
int appColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.news_page_layout);
configViews();
}
private void configViews() {
recyclerView = this.findViewById(R.id.news_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(NewsPage.this));
recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
Realm newsRealm = Realm.getDefaultInstance();
RealmResults<NewsRealmModel> temp = newsRealm.where(NewsRealmModel.class).findAll();
mNewsList = new ArrayList<>();
for (int i = 0; i < temp.size(); i++) {
mNewsList.add(temp.get(i));
}
adapter = new NewsAdapter(mNewsList,getApplicationContext());
Log.d( "adapter value is"+"", String.valueOf( adapter ) );
recyclerView.setAdapter(adapter);
}
}
And the new Controller Class
public class NewsController {
private static final String TAG = NewsController.class.getSimpleName();
private UserCallbackListener mListener;
private NewsRestApiManager mApiManager;
private AppImage appImages;
Realm myNews_realm;
ArrayList<String> title_list = new ArrayList<>();
GlobalClass globalClass = new GlobalClass();
public NewsController(UserCallbackListener listener) {
mListener = listener;
mApiManager = new NewsRestApiManager();
}
public void startFetching() {
myNews_realm = Realm.getDefaultInstance();
mApiManager.getNewsApi().getNews(new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d(TAG, "JSON :: " + s);
try {
JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
Log.d("-----Start Fetching---", jsonObject.optString("title"));
if (!myNews_realm.isInTransaction()) {
myNews_realm.beginTransaction();
NewsRealmModel news = new NewsRealmModel();
....... data
}
myNews_realm.copyToRealm(news);
myNews_realm.commitTransaction();
mListener.onFetchProgressNews(news);
} else {
myNews_realm.commitTransaction();
}
}
} catch (JSONException e) {
mListener.onFetchFailed();
}
mListener.onFetchComplete();
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error :: " + error.getMessage());
mListener.onFetchComplete();
}
});
}
public interface UserCallbackListener {
void onFetchProgressNews(NewsRealmModel news);
void onFetchComplete();
void onFetchFailed();
}
}
To do your database processing on a background thread using Volley, you need to extend Request<T> and do the Realm write in parseNetworkResponse method.
public class RealmGsonObjectRequest<T, M extends RealmModel> extends Response<Void> {
...
#Override
protected Response<Void> parseNetworkResponse(
NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
T data = gson.fromJson(json, clazz);
// write the downloaded data into the Realm on bg thread
try(Realm r = Realm.getDefaultInstance()) {
M model = mapper.toModel(data);
r.executeTransaction((realm) -> {
realm.insertOrUpdate(model);
});
}
return Response.success(null,
HttpHeaderParser.parseCacheHeaders(response)
);
} // handle errors
}
You might need a RealmGsonListRequest as well.
public class RealmGsonListRequest<T, M extends RealmModel> extends Response<Void> {
...
#Override
protected Response<Void> parseNetworkResponse(
NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
List<T> data = gson.fromJson(json, new TypeToken<ArrayList<T>>() {}.getType());
// write the downloaded data into the Realm on bg thread
try(Realm r = Realm.getDefaultInstance()) {
M model = mapper.toModel(data);
r.executeTransaction((realm) -> {
realm.insertOrUpdate(model);
});
}
return Response.success(null,
HttpHeaderParser.parseCacheHeaders(response)
);
} // handle errors
}
For more information, refer to the official Volley tutorial on how to create a custom Volley request type.

Getting error:No adapter attached; skipping layout in recyclerview

I tried to fetch the json values from url and shows in listview with adapter in recylerview. but the listview is empty and getting this error 'No adapter attached; skipping layout'. When I tried with the below code its working
for (int i = index; i < end; i++) {
User user = new User();
user.setName("Name " + i);
mUsers.add(user);
}
Here is my part of code, if needed I'll upload complete code
public class OtherNews extends AppCompatActivity {
JSONArray jsonarray;
private RecyclerView mRecyclerView;
private List<User> mUsers = new ArrayList<>();
private UserAdapter mUserAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mUserAdapter = new UserAdapter();
new DownloadJSON().execute();
mUserAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
Log.e("haint", "Load More");
mUsers.add(null);
mUserAdapter.notifyItemInserted(mUsers.size() - 1);
//Load more data for reyclerview
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Log.e("haint", "Load More 2");
//Remove loading item
mUsers.remove(mUsers.size() - 1);
mUserAdapter.notifyItemRemoved(mUsers.size());
//Load data
int index = mUsers.size();
int end = index + 20;
for (int i = index; i < end; i++) {
User user = new User();
user.setName("Name " + i);
user.setEmail("alibaba" + i + "#gmail.com");
mUsers.add(user);
}
mUserAdapter.notifyDataSetChanged();
mUserAdapter.setLoaded();
}
}, 5000);
}
});
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
private static final String TAG = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall("http://xxxxxxxxx.in/projects/falcon/getallnews.php?page=2");
if (jsonStr != null) {
try {
JSONObject jsonobject = new JSONObject(jsonStr);
jsonarray = jsonobject.getJSONArray("news");
// Getting JSON Array node
for (int i = 0; i < jsonarray.length(); i++) {
User user = new User();
String title = jsonobject.getString("title");
user.setName(title);
mUsers.add(user);
}
} catch (final JSONException e) {
}
} else {
Log.d(TAG, "someOther)");
}
return null;
}
#Override
protected void onPostExecute(Void args) {
mRecyclerView.setAdapter(mUserAdapter);
}
}
I get the value in this line of code, but couldn't set in list view.
String title = jsonobject.getString("title");
user.setName(title);
The issue is exactly like it sounds, an adapter is not being attached when it needs it. You don't attach it until onPostExecute. Just attach it right from the beginning:
mRecyclerView = (RecyclerView) findViewById(R.id.recycleView);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mUserAdapter = new UserAdapter();
mRecyclerView.setAdapter(mUserAdapter);
As you modify the adapter in other parts of the code, your RecyclerView will update automatically, so long as you call notifyDataSetChanged() or some related method.

Pass position of the item of recycler view to open up a new acitivity

How can i pass the position of item using intent to start a new activity?
I want to start a new activity called single which displays the rating of the movie correspondingly..pls help
I have been trying this for the past two days.
Here is the code:
public class NowPlaying extends Fragment {
private static final String TAG = NowPlaying.class.getSimpleName();
// Movies json url
private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
private ProgressDialog pDialog;
private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;
NowPlayingAdapter adapter;
RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
toolbar.setTitle("Now playing");
recyclerView = (RecyclerView) v.findViewById(R.id.cardList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new NowPlayingAdapter(getActivity(), bottom);
recyclerView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
v.getContext().startActivity(i);
}
});
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
NowPlayingInfo trailer = new NowPlayingInfo();
trailer.setTitle(jsonObject.getString("original_title"));
String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
trailer.setImage(iss);
bottom.add(trailer);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
NowPlayingInfo _nowPlaying = bottom.get(position);
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
i.putExtra("ISS", _nowPlaying.getImage()); //you can put your current playing info.
i.putExtra("POSITION", position); //you can put your position to next activity.
v.getContext().startActivity(i);
}
});
Add this in your SingleInfo Class.
String _rating = "";
public String get_rating() {
return _rating;
}
public void set_rating(String _rating) {
this._rating = _rating;
}
Add this in your Single class -
int _currentPos = 0 ; //Global variable .
_currentPos = getIntent().getIntExtra("position", 0);// paste this in onCreate()
Add this code in onResponse of Single Class -
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SingleInfo s = new SingleInfo();
s.set_rating(jsonObject.getString("rating"));
single.add(s);
}
//changed by Shoeb
SingleInfo _singleInfo = single.get(_currentPos); //position from previous activity
textView.setText(_singleInfo.get_rating());
//end changes
} catch (JSONException e) {
e.printStackTrace();
}
Add an extra to your intent
i.putExtra("position",position);
And on the other activity:
getIntent().getIntExtra("position", 0);

Categories

Resources