Please I have been trying to display json data from recycler view to another activity but only the textview displays and the image does not. This is my code
public class MainActivity extends AppCompatActivity {
public String content;
public static MainActivity parse(JSONObject object){
MainActivity post=new MainActivity();
post.content = Html.fromHtml(object.optString("content")).toString();
return post;
}
ImageView thumbnail;
TextView title;
private static final String TAG = "RecyclerViewExample";
private SwipeRefreshLayout swipeRefreshLayout;
private List<FeedItem> feedsList;
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
private ProgressBar progressBar;
public MainActivity(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_list);
// Initialize recycler view
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
// Downloading data from below url
final String url = "http://street2view.com/api/get_recent_posts/";
new AsyncHttpTask().execute(url);
}
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
progressBar.setVisibility(View.GONE);
if (result == 1) {
adapter = new MyRecyclerAdapter(MainActivity.this, feedsList);
mRecyclerView.setAdapter(adapter);
} else {
Toast.makeText(MainActivity.this, "Check Your Internet Connection", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (item.getItemId() == R.id.about) {
Intent settingsActivityIntent = new Intent();
settingsActivityIntent.setClass(this, AboutActivity.class);
this.startActivityForResult(settingsActivityIntent, 111);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Quit")
.setMessage("Do you wish to exit the app?")
.setCancelable(false)
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).create().show();
}
public String stripHtmlTags(String html) {
return Html.fromHtml(html).toString();
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("posts");
feedsList = new ArrayList<>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.optString("title"));
item.setContent(post.optString("content"));
item.setdate(post.optString("date"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setAttachmentUrl(attachment.getString("url"));
}
JSONArray categories = post.getJSONArray("categories");
if (null != categories && categories.length() > 0) {
JSONObject attachment = categories.getJSONObject(0);
if (categories != null)
item.setCategories(attachment.getString("title"));
}
feedsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
and this is the adapter class in which i use to send the data from the recycler view to the second activity
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view,mContext, (ArrayList<FeedItem>) feedItemList);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeedItem feedItem = feedItemList.get(i);
//Download image using picasso library
Glide.with(mContext).load(feedItem.getAttachmentUrl())
.error(R.color.list_item_title)
.placeholder(R.color.list_item_title)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText((feedItem.getTitle()));
customViewHolder.textView2.setText(feedItem.getdate());
customViewHolder.categories.setText(feedItem.getCategories());
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected ImageView imageView;
protected TextView textView2;
protected TextView textView;
protected TextView content;
protected TextView categories;
public RelativeLayout relativeLayout;
ArrayList<FeedItem> feeditem = new ArrayList<FeedItem>();
Context ctx;
public CustomViewHolder(View view, Context ctx, ArrayList<FeedItem> feeditem) {
super(view);
view.setOnClickListener(this);
this.ctx = ctx;
this.feeditem = feeditem;
this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
this.textView2 = (TextView) view.findViewById(R.id.date);
this.categories = (TextView) view.findViewById(R.id.categories);
this.textView = (TextView) view.findViewById(R.id.title);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
FeedItem feeditem = this.feeditem.get(position);
Intent intent = new Intent(this.ctx,Main2Activity.class);
intent.putExtra("title",feeditem.getTitle());
intent.putExtra("content",feeditem.getContent());
Html.fromHtml(String.valueOf(intent.putExtra("content",feeditem.getContent()))).toString();
intent.putExtra("thumbnail",feeditem.getAttachmentUrl());
this.ctx.startActivity(intent);
}
}
}
and this is the second activity where i want to display the json data (when i run the application the textview shows but the imageview dosent thanks in advance)
public class Main2Activity extends AppCompatActivity {
ImageView imageView;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView = (ImageView)findViewById(R.id.contentImage);
textView = (TextView)findViewById(R.id.title2);
textView.setText(getIntent().getStringExtra("title"));
imageView.setImageResource(getIntent().getIntExtra("thumbnail", 00));
}}
You can try this
public class Main2Activity extends AppCompatActivity {
ImageView imageView;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageView = (ImageView) findViewById(R.id.contentImage);
textView = (TextView) findViewById(R.id.title2);
String title = getIntent().getStringExtra("title");
String thumbnail = getIntent().getStringExtra("thumbnail");
textView.setText(title);
// set image here
Glide.with(this).load(thumbnail)
.into(imageView);
}
}
Related
Calling my async task class from my oncreate in OpensubcontentActivity, it is executing fine but while calling the same async task class from vivcontentAdapter in onBindViewHolder it is giving null pointer error in progressdialog.
OpensubcontentActivity
public class OpenSubContentActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private vivcontentAdapter vivcontentAdapteradapter;
static String stack_info[] = new String[10];
static int top = -1;
static String ObjectId;
static List<Information> data_content = new ArrayList<>();
public static Map info_map = null;
Boolean file_flag;
File file;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_sub_content);
setEveryThing();
Intent mIntent = getIntent();
context = this;
ObjectId = mIntent.getStringExtra("CabinetID");
new getData().execute();
}
public void setEveryThing() {
floatingActionMenu = (FloatingActionMenu) findViewById(R.id.floating_menu);
newfolder = (FloatingActionButton) findViewById(R.id.idtem__folder);
newdoc = (FloatingActionButton) findViewById(R.id.idtem_doc);
upload = (FloatingActionButton) findViewById(R.id.idtem_upload);
capture = (FloatingActionButton) findViewById(R.id.idtem_photo);
toolbar = (Toolbar) findViewById(R.id.toolBar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(("Example"));
recyclerView = (RecyclerView) findViewById(R.id.list_file);
vivcontentAdapteradapter = new vivcontentAdapter(this, data_content);
recyclerView.setAdapter(vivcontentAdapteradapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
class getData extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(OpenSubContentActivity.this);
pDialog.setMessage("Fetching Content...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
}
#Override
protected String doInBackground(Void... voids) {
info_map = new HashMap();
String title = "";
String results = "";
int count = 0;
if (ObjectId.startsWith("0c")) {
Log.d("first", "coming");
CmisObject object = MainActivity.session.getObject(MainActivity.session.createObjectId(ObjectId));
Folder folder = (Folder) object;
//Document document = (Document)object;
OperationContext operationContext = MainActivity.session.createOperationContext();
ItemIterable<CmisObject> childrenn = folder.getChildren(operationContext);
ItemIterable<CmisObject> page = childrenn.getPage();
Iterator<CmisObject> pageItems = page.iterator();
while (pageItems.hasNext()) {
CmisObject item = null;
item = pageItems.next();
//System.out.println(item.getId());
if (item != null && item.getName() != null) {
if (item.getId().startsWith("0b")) {
Information info = new Information();
info.title = item.getName();
info.iconId = icons[0];
info.folderId_open_Id = item.getId();
title = title + "\n" + item.getName();
info_map.put(count, info.folderId_open_Id);
data_content.add(info);
count++;
}
return results;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
vivcontentAdapteradapter.notifyDataSetChanged();
}
}
}
}
}
}
vivcontentAdapter
In this activity i am calling async task class of opensubcontentactivity.But while calling from here in progress dialog it is giving error in asynctask class getData()
Using -
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
vivcontentAdapter
public class vivcontentAdapter extends RecyclerView.Adapter<vivcontentAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Information> data_content = Collections.emptyList();
Context context;
public vivcontentAdapter(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data_content = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final vivcontentAdapter.MyViewHolder holder, final int position) {
Information current = data_content.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
holder.keyicon.setImageResource(current.checkin_icon);
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String store_objectID = (String) OpenSubContentActivity.info_map.get(position);
if (store_objectID.startsWith("0b")) {
OpenSubContentActivity.top++;
OpenSubContentActivity.stack_info[OpenSubContentActivity.top] = store_objectID; OpenSubContentActivity.ObjectId = store_objectID;
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
} else {
OpenSubContentActivity.ObjectId = store_objectID;
OpenSubContentActivity openSubContentActivity=new OpenSubContentActivity();
openSubContentActivity.new getData().execute();
}
Toast.makeText(context, "Open", Toast.LENGTH_SHORT).show();
}
});
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View v) {
//Display option menu
});
}
#Override
public int getItemCount() {
return data_content.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title, txtOptionDigit;
ImageView icon, keyicon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textvw);
icon = (ImageView) itemView.findViewById(R.id.imageView);
keyicon = (ImageView) itemView.findViewById(R.id.key_icon);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
}
}
}
}
Error-
03-30 00:21:40.690 10385-10385/reva.irving E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-30 00:21:40.690 10385-10385/reva.irving E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
03-30 00:22:04.228 10385-10385/reva.irving E/AndroidRuntime: FATAL EXCEPTION: main
Process: reva.irving, PID: 10385
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at reva.irving.OpenSubContentActivity$getData.onPreExecute(OpenSubContentActivity.java:103)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:620)
at android.os.AsyncTask.execute(AsyncTask.java:567)
at reva.irving.OpenSubContentActivity.call(OpenSubContentActivity.java:84)
at reva.irving.vivcontentAdapter$1.onClick(vivcontentAdapter.java:59)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6205)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
To perform clicks in a Recycler view you need to change your adapter. Add an interface to act as the click listener and implement it in your activity, like so:
public class vivcontentAdapter extends RecyclerView.Adapter<vivcontentAdapter.MyViewHolder> {
private final LayoutInflater inflater;
List<Information> data_content = Collections.emptyList();
Context context;
private OnClickItem clickListener;
public vivcontentAdapter(Context context, List<Information> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data_content = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final vivcontentAdapter.MyViewHolder holder, final int position) {
Information current = data_content.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
holder.keyicon.setImageResource(current.checkin_icon);
holder.txtOptionDigit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View v) {
//Display option menu
});
}
#Override
public int getItemCount() {
return data_content.size();
}
public void setClickListener(OnClickItem listener){
this.listener = listener;
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title, txtOptionDigit;
ImageView icon, keyicon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textvw);
icon = (ImageView) itemView.findViewById(R.id.imageView);
keyicon = (ImageView) itemView.findViewById(R.id.key_icon);
txtOptionDigit = (TextView) itemView.findViewById(R.id.txtOptionDigit);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
listener.onClickListItem(pos);
}
}
public interface OnClickItem{
void onClickListItem(int position);
}
}
Now in your activity you can catch the cliicks and run the async task:
public class OpenSubContentActivity extends AppCompatActivity implements vivcontentAdapter.OnClickItem{
private RecyclerView recyclerView;
private vivcontentAdapter vivcontentAdapteradapter;
static String stack_info[] = new String[10];
static int top = -1;
static String ObjectId;
static List<Information> data_content = new ArrayList<>();
public static Map info_map = null;
Boolean file_flag;
File file;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_sub_content);
setEveryThing();
Intent mIntent = getIntent();
context=this;
ObjectId = mIntent.getStringExtra("CabinetID");
new getData().execute();
}
public void setEveryThing() {
floatingActionMenu = (FloatingActionMenu) findViewById(R.id.floating_menu);
newfolder = (FloatingActionButton) findViewById(R.id.idtem__folder);
newdoc = (FloatingActionButton) findViewById(R.id.idtem_doc);
upload = (FloatingActionButton) findViewById(R.id.idtem_upload);
capture = (FloatingActionButton) findViewById(R.id.idtem_photo);
toolbar = (Toolbar) findViewById(R.id.toolBar);
toolbar.setTitleTextColor(0xFFFFFFFF);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(("Example"));
recyclerView = (RecyclerView) findViewById(R.id.list_file);
vivcontentAdapteradapter = new vivcontentAdapter(this, data_content);
vivcontentAdapteradapter.setClickListener(this);
recyclerView.setAdapter(vivcontentAdapteradapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public void onClickListItem(int position){
new getData().execute();
}
class getData extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(OpenSubContentActivity.this);
pDialog.setMessage("Fetching Content...");
pDialog.show();
pDialog.setCanceledOnTouchOutside(false);
}
#Override
protected String doInBackground(Void... voids) {
info_map = new HashMap();
String title = "";
String results = "";
int count = 0;
if (ObjectId.startsWith("0c")) {
Log.d("first", "coming");
CmisObject object = MainActivity.session.getObject(MainActivity.session.createObjectId(ObjectId));
Folder folder = (Folder) object;
//Document document = (Document)object;
OperationContext operationContext = MainActivity.session.createOperationContext();
ItemIterable<CmisObject> childrenn = folder.getChildren(operationContext);
ItemIterable<CmisObject> page = childrenn.getPage();
Iterator<CmisObject> pageItems = page.iterator();
while (pageItems.hasNext()) {
CmisObject item = null;
item = pageItems.next();
//System.out.println(item.getId());
if (item != null && item.getName() != null) {
if (item.getId().startsWith("0b")) {
Information info = new Information();
info.title = item.getName();
info.iconId = icons[0];
info.folderId_open_Id = item.getId();
title = title + "\n" + item.getName();
info_map.put(count, info.folderId_open_Id);
data_content.add(info);
count++;
}
return results;
}
#Override
protected void onPostExecute(String s) {
pDialog.dismiss();
vivcontentAdapteradapter.notifyDataSetChanged();
}
}
}
I have an Interface implemented in ProductListAdapter class which is a list adapter. Items in this list have three input fields. to keep track of those values I have implemented a class MyCustomEditTextListener which extends a TextWatcher class. This class simply create array list of edited data. I want to get reference to array list every time it changes from fragment which contains list view. For that I have implemented DataChangedListener
ProductListAdapter.java
public class ProductListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private LayoutInflater inflater;
private ArrayList<Products> listData;
private ArrayList<Products> editedData;
private Context context;
private DataChangedListener dataChangedListener;
private static final int ITEM = 0;
private static final int LOADING = 1;
private static final int QUANTITY = 5;
private static final int FREE_QUANTITY = 10;
private static final int DISCOUNT = 15;
public ProductListAdapter(ArrayList<Products> listData, ArrayList<Products> editedData, Context context) {
this.listData = listData;
this.context = context;
this.editedData = editedData;
inflater = LayoutInflater.from(this.context);
}
public void updateData(ArrayList<Products> data) {
this.listData = data;
notifyDataSetChanged();
}
public void setDataChangedListener(DataChangedListener listener) {
this.dataChangedListener = listener;
}
#Override
public int getItemViewType(int position) {
return listData.get(position) == null ? LOADING : ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
switch (viewType) {
case ITEM:
viewHolder = getViewHolder(parent, inflater);
break;
case LOADING:
View v2 = inflater.inflate(R.layout.list_footer, parent, false);
viewHolder = new LoadingVH(v2);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Products productObject = listData.get(position);
switch (getItemViewType(position)) {
case ITEM:
for(int i=0; i<editedData.size(); i++){
if(productObject.getProductId().equals(editedData.get(i).getProductId())){
productObject.setQuantity(editedData.get(i).getQuantity());
productObject.setFreeQuantity(editedData.get(i).getFreeQuantity());
productObject.setDiscount(editedData.get(i).getDiscount());
}
}
String productName = productObject.getProductName();
String quantityValue = productObject.getQuantity();
String freeQuantityValue = productObject.getFreeQuantity();
String discountValue = productObject.getDiscount();
String quantityInHand = productObject.getQuantityInHand();
String price = productObject.getWholeSalePrice();
ContentViewHolder movieVH = (ContentViewHolder) holder;
movieVH.productName.setText(productName);
movieVH.stock.setText(quantityInHand);
movieVH.price.setText("Rs."+price);
movieVH.quantityEditTextListener.updatePosition(movieVH.getLayoutPosition());
movieVH.quantity.setText(quantityValue);
movieVH.freeQuantityEditTextListener.updatePosition(movieVH.getLayoutPosition());
movieVH.freeQuantity.setText(freeQuantityValue);
movieVH.discountEditTextListener.updatePosition(movieVH.getLayoutPosition());
movieVH.discount.setText(discountValue);
movieVH.quantity.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
return false;
}
});
break;
case LOADING:
//Do nothing
break;
}
}
#Override
public int getItemCount() {
return listData == null ? 0 : listData.size();
}
#NonNull
private RecyclerView.ViewHolder getViewHolder(ViewGroup parent, LayoutInflater inflater) {
RecyclerView.ViewHolder viewHolder;
View view = inflater.inflate(R.layout.custom_product_list_item, parent, false);
viewHolder = new ContentViewHolder(view, new MyCustomEditTextListener()
, new MyCustomEditTextListener(), new MyCustomEditTextListener());
return viewHolder;
}
/**
* View holder for main container
*/
public class ContentViewHolder extends RecyclerView.ViewHolder{
private TextView productName;
private EditText quantity;
private EditText freeQuantity;
private EditText discount;
private TextView stock;
private TextView price;
private MyCustomEditTextListener quantityEditTextListener;
private MyCustomEditTextListener freeQuantityEditTextListener;
private MyCustomEditTextListener discountEditTextListener;
public ContentViewHolder(View itemView, MyCustomEditTextListener textListener
, MyCustomEditTextListener textListener2, MyCustomEditTextListener textListener3) {
super(itemView);
productName = (TextView) itemView.findViewById(R.id.product_name_data);
quantity = (EditText) itemView.findViewById(R.id.quantity_1_edit_text);
freeQuantity = (EditText) itemView.findViewById(R.id.quantity_2_edit_text);
discount = (EditText) itemView.findViewById(R.id.quantity_3_edit_text);
stock = (TextView) itemView.findViewById(R.id.quantity_in_hand_value);
price = (TextView) itemView.findViewById(R.id.price_value);
quantityEditTextListener = textListener;
quantityEditTextListener.setEditTextType(QUANTITY);
freeQuantityEditTextListener = textListener2;
freeQuantityEditTextListener.setEditTextType(FREE_QUANTITY);
discountEditTextListener = textListener3;
discountEditTextListener.setEditTextType(DISCOUNT);
this.quantity.addTextChangedListener(quantityEditTextListener);
this.freeQuantity.addTextChangedListener(freeQuantityEditTextListener);
this.discount.addTextChangedListener(discountEditTextListener);
}
}
/**
* View holder to display loading list item
*/
protected class LoadingVH extends RecyclerView.ViewHolder {
public LoadingVH(View itemView) {
super(itemView);
}
}
/**
* textWatcher for to keep track of changed data.
*/
private class MyCustomEditTextListener implements TextWatcher {
private int position;
private int type;
public void updatePosition(int position) {
this.position = position;
}
public void setEditTextType(int type) {
this.type = type;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
// no op
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (type == QUANTITY) {
listData.get(position).setQuantity(charSequence.toString());
} else if (type == FREE_QUANTITY) {
listData.get(position).setFreeQuantity(charSequence.toString());
} else if (type == DISCOUNT) {
listData.get(position).setDiscount(charSequence.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
boolean matchFound = false;
if(s.toString().length()>0){
for (int i=0;i<editedData.size();i++){
if(editedData.get(i).getProductId()
.equals(listData.get(position).getProductId())){
matchFound = true;
if (type == QUANTITY) {
editedData.get(i).setQuantity(s.toString());
} else if (type == FREE_QUANTITY) {
editedData.get(i).setFreeQuantity(s.toString());
} else if (type == DISCOUNT) {
editedData.get(i).setDiscount(s.toString());
}
}
}
if(!matchFound){
editedData.add(listData.get(position));
}
if(dataChangedListener!=null){
dataChangedListener.onDataChanged(editedData);
}
}
}
}
public interface DataChangedListener{
void onDataChanged(ArrayList<Products> editedData);
}
In my OrderEditFragment i'm trying to implement that interface to do necessary calculations.
OrderEditFragment.java
public class OrderEditFragment extends Fragment implements ProductListAdapter.DataChangedListener {
private LinearLayoutManager layoutManager;
private RecyclerView productRecyclerView;
private static ProductListAdapter productListAdapter;
private String employeeId;
private static ArrayList<Products> editedData;
private static ArrayList<Products> productsData;
private SharedPreferences sharedpreferences;
private final static OkHttpClient client = new OkHttpClient();
public OrderEditFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fragment_order_edit, container, false);
initComponents(inflate);
return inflate;
}
private void initComponents(View view) {
productRecyclerView = (RecyclerView) view.findViewById(R.id.product_edit_recycler_view);
progressView = (CircularProgressView) view.findViewById(R.id.progress_view);
layoutManager = new LinearLayoutManager(getContext());
sharedpreferences = getActivity().getSharedPreferences("dgFashionPref", Context.MODE_PRIVATE);
employeeId = sharedpreferences.getString("employee_id","");
productsData = new ArrayList<>();
editedData = new ArrayList<>();
isLoading = false;
isLastPage = false;
isFirstLoad = true;
isSearch = false;
new GetProductListGetRequest(getContext(), productRecyclerView, layoutManager)
.execute(RestConnection.PRODUCT_LIST_GET
+ RestConnection.CUSTOMER_ID_FOR_NAME + employeeId);
}
#Override
public void onDataChanged(ArrayList<Products> editedData) {
Log.d(TAG,editedData.toString());
}
/**
* AsyncTask class which handel the GET request to get product list
**/
public static class GetProductListGetRequest extends AsyncTask<String, Void, String>{
private WeakReference<Context> ActivityWeakReference;
private WeakReference<RecyclerView> recyclerViewWeakReference;
private WeakReference<RecyclerView.LayoutManager> layoutManagerWeakReference;
public GetProductListGetRequest(Context activity, RecyclerView recyclerView
, RecyclerView.LayoutManager layoutManager) {
ActivityWeakReference = new WeakReference<>(activity);
recyclerViewWeakReference = new WeakReference<>(recyclerView);
layoutManagerWeakReference = new WeakReference<>(layoutManager);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String urlEndPoint = params[0];
Request request = new Request.Builder()
.url(RestConnection.API_BASE + urlEndPoint)
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
if( productsData.size()>0){
productsData.remove(productsData.size() - 1);
}
JSONArray responseBody;
try {
if (response != null && ActivityWeakReference.get() != null) {
responseBody = new JSONArray(response);
for (int i = 0; i < responseBody.length(); i++) {
JSONObject row = responseBody.getJSONObject(i);
String productId = row.getString("ProductID");
String productName = row.getString("Name");
String unit = row.getString("Unit");
String wholeSalePrice = row.getString("WSalePrice");
String packSize = row.getString("PackSize");
String retailPrice = row.getString("RetailPrice");
String costPrice = row.getString("CostPrice");
String qtyInHand = row.getString("QtyInHand");
Products productObj = new Products();
productObj.setProductName(productName);
productObj.setProductId(productId);
productObj.setUnit(unit);
productObj.setWholeSalePrice(wholeSalePrice);
productObj.setPackSize(packSize);
productObj.setRetailPrice(retailPrice);
productObj.setCostPrice(costPrice);
productObj.setQuantityInHand(qtyInHand);
productsData.add(productObj);
}
productListAdapter = new ProductListAdapter(productsData, editedData, ActivityWeakReference.get());
productListAdapter.setDataChangedListener(ActivityWeakReference.get());
recyclerViewWeakReference.get().setAdapter(productListAdapter);
recyclerViewWeakReference.get().setLayoutManager(layoutManagerWeakReference.get());
recyclerViewWeakReference.get().addItemDecoration(new RecyclerViewDivider(2));
} else {
Toast.makeText(ActivityWeakReference.get(), "Can't connect to the server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e)
{
Log.d(TAG, "Get customer details onPostExecute :" + e.getLocalizedMessage());
}
}
}
/**
* A class that define space between list items
*/
private static class RecyclerViewDivider extends RecyclerView.ItemDecoration {
int space;
public RecyclerViewDivider(int space) {
this.space = space;
}
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.bottom = space;
if (parent.getChildLayoutPosition(view) == 0) {
outRect.top = space;
}
}
}
}
As you can see I'm trying to instantiate interface inside AsyncTask class soon after created productListAdapter object by calling setDataChangedListener(DataChangedListener listener); method. But it did not take ActivityWeakReference.get() as a valid parameter. I have done slimier thing before with list adapter to bring custom created onListItemClick event to activity. In those cases ActivityWeakReference.get() works fine. I think this is happening because I'm in a fragment, But I can't figure out which object I should pass. I need to create Adapter inside AsyncTask because i have implemented pagination for list view. I remove those codes to make this post short. Please help.
Found the solution. You need to pass fragment object to interface not the activity.
Here's my fragment class now.
/**
* AsyncTask class which handel the GET request to get product list
**/
public static class GetProductListGetRequest extends AsyncTask<String, Void, String>{
private WeakReference<OrderEditFragment> fragmentWeakReference;
private WeakReference<RecyclerView> recyclerViewWeakReference;
private WeakReference<RecyclerView.LayoutManager> layoutManagerWeakReference;
public GetProductListGetRequest(OrderEditFragment fragment, RecyclerView recyclerView
, RecyclerView.LayoutManager layoutManager) {
fragmentWeakReference = new WeakReference<>(fragment);
recyclerViewWeakReference = new WeakReference<>(recyclerView);
layoutManagerWeakReference = new WeakReference<>(layoutManager);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String urlEndPoint = params[0];
Request request = new Request.Builder()
.url(RestConnection.API_BASE + urlEndPoint)
.build();
//Log.d(TAG,RestConnection.API_BASE + urlEndPoint);
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String response) {
if( productsData.size()>0){
productsData.remove(productsData.size() - 1);
}
JSONArray responseBody;
//Log.d(TAG,response);
try {
if (response != null && fragmentWeakReference.get() != null) {
responseBody = new JSONArray(response);
for (int i = 0; i < responseBody.length(); i++) {
JSONObject row = responseBody.getJSONObject(i);
String productId = row.getString("ProductID");
String productName = row.getString("Name");
String unit = row.getString("Unit");
String wholeSalePrice = row.getString("WSalePrice");
String packSize = row.getString("PackSize");
String retailPrice = row.getString("RetailPrice");
String costPrice = row.getString("CostPrice");
String qtyInHand = row.getString("QtyInHand");
Products productObj = new Products();
productObj.setProductName(productName);
productObj.setProductId(productId);
productObj.setUnit(unit);
productObj.setWholeSalePrice(wholeSalePrice);
productObj.setPackSize(packSize);
productObj.setRetailPrice(retailPrice);
productObj.setCostPrice(costPrice);
productObj.setQuantityInHand(qtyInHand);
productsData.add(productObj);
}
/** if lower limit and upper limit change, change responseBody.length()<10 respectively **/
if (responseBody.length() == 0 || responseBody.length() < 10) {
isLastPage = true;
}
if (isFirstLoad) {
progressView.setVisibility(View.GONE);
recyclerViewWeakReference.get().setVisibility(View.VISIBLE);
productListAdapter = new ProductListAdapter(productsData, editedData, fragmentWeakReference.get().getContext());
productListAdapter.setDataChangedListener(fragmentWeakReference.get());
recyclerViewWeakReference.get().setAdapter(productListAdapter);
recyclerViewWeakReference.get().setLayoutManager(layoutManagerWeakReference.get());
recyclerViewWeakReference.get().addItemDecoration(new RecyclerViewDivider(2));
isFirstLoad = false;
} else {
productListAdapter.updateData(productsData);
isLoading = false;
}
} else {
Toast.makeText(fragmentWeakReference.get().getContext(), "Can't connect to the server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e)
{
Log.d(TAG, "Get customer details onPostExecute :" + e.getLocalizedMessage());
}
}
}
And create AsyncTask object like bellow.
new GetProductListGetRequest(this, productRecyclerView, layoutManager)
.execute(RestConnection.PRODUCT_LIST_GET
+ RestConnection.CUSTOMER_ID_FOR_NAME + employeeId);
i have a series of items in recyclerview .i want to set on click listener and open a description page of specific item and set data from json url. i have already made an adapter for description screen and a bean class. i dont know how to set adapter on layout. is it possible to set an adapter on linear layout to show static content from json url?
My code is :
Description activity
private class MakeRequestForGetDescription extends AsyncTask<String, Void, String> {
ProgressDialog Pdialog;
private String response;
private MakeServiceClass makeServiceClass = new MakeServiceClass();
#Override
protected void onPreExecute() {
Pdialog = new ProgressDialog(getActivity());
Pdialog.setMessage("Please Wait..");
Pdialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
HashMap<String, String> parms = new HashMap<String, String>();
response = makeServiceClass.makeServiceConnectionGet(ConstUrl.DESCRP_URLS);
Log.e("response ads", response);
} catch (Exception ex) {
ex.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(response);
if (Pdialog != null) {
Pdialog.dismiss();
}
if (response != null) {
try {
JSONObject mainObject = new JSONObject(response);
if (mainObject.has("status")) {
String Status = mainObject.getString("status");
String img_url = "";
if (Status.equalsIgnoreCase("200")) {
if (mainObject.has("img_url")) {
img_url = mainObject.getString("img_url");
Log.e("img_url", img_url);
}
if (mainObject.has("details")) {
JSONArray datArray = mainObject.getJSONArray("details");
descriptionBeanArrayList = new ArrayList<>();
if (datArray.length() > 0) {
for (int i = 0; i < datArray.length(); i++) {
DescriptionBean descriptionBean = new DescriptionBean();
JSONObject internalDataObject = datArray.getJSONObject(i);
if (internalDataObject.has("id")) {
descriptionBean.setId(internalDataObject.getString("id"));
}
if (internalDataObject.has("title_en")) {
descriptionBean.setTitle_en(internalDataObject.getString("title_en"));
}
if (internalDataObject.has("ad_description_en")) {
descriptionBean.setAd_description_en(internalDataObject.getString("ad_description_en"));
}
if (internalDataObject.has("price")) {
descriptionBean.setPrice(internalDataObject.getString("price"));
}
if (internalDataObject.has("km_driven")) {
descriptionBean.setKm_driven(internalDataObject.getString("km_driven"));
}
if (internalDataObject.has("image_file")) {
descriptionBean.setImage_file("http://" + img_url + internalDataObject.getString("image_file"));
}
descriptionBeanArrayList.add(descriptionBean);
}
setAdapterForDescription();
}
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void setAdapterForDescription() {
DescriptionAdapter adapter = new DescriptionAdapter(getActivity(), descriptionBeanArrayList);
}
}
Description Adapter
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.fragment_description, parent,false);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
viewHolder.tvRate = (TextView) convertView.findViewById(R.id.tvRate);
viewHolder.tvMiles = (TextView) convertView.findViewById(R.id.tvMiles);
viewHolder.et_description = (EditText) convertView.findViewById(R.id.et_description);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
//setdata
viewHolder.tvTitle.setText(descriptionBeanArrayList.get(position).getTitle_en());
viewHolder.tvRate.setText(descriptionBeanArrayList.get(position).getPrice());
viewHolder.tvMiles.setText(descriptionBeanArrayList.get(position).getKm_driven());
viewHolder.et_description.setText(descriptionBeanArrayList.get(position).getAd_description_en());
Log.e("s", descriptionBeanArrayList.get(position).getImage_file());
//Glide.with(mContext).load("www.apnikheti.com/upload/buysell/idea99A4.jpg").into(viewHolder.iv_picofproduct);
Picasso.with(mContext).load(descriptionBeanArrayList.get(position).getImage_file()).into(viewHolder.iv_picofproduct, new Callback() {
#Override
public void onSuccess() {
Log.e("s", "sucess");
}
#Override
public void onError() {
Log.e("s", "failed");
}
});
Picasso.with(mContext).setLoggingEnabled(true);
return convertView;
}
public class ViewHolder {
private TextView tvTitle,tvRate,tvMiles;
private EditText et_description;
public ImageView iv_picofproduct;
}
}
This is my code which is used to retrieve data from url (Json Data) and load it into a recyclerview using adapter and passing the same values to another activity.
MyActivity
public class Video_List extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//private GridLayoutManager layoutManager;
private List<Video_Details> videodetails;
public static final String VideoID = "v_id";
public static final String ID = "id";
public static final String Title = "title";
public static final String Thumb = "thumb";
public static final String url = "http://115.115.122.10/paul/api/videos.php?start=1&count=10";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video__list);
getdata();
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
//layoutManager = new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
videodetails = new ArrayList<>();
}
private void getdata(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing progress dialog
loading.dismiss();
Log.d("count",response.toString());
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.dismiss();
Log.d("infoz","777"+error.getMessage());
Toast.makeText(getApplicationContext(),"No data Found",Toast.LENGTH_LONG).show();
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
try {
for (int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
Video_Details video = new Video_Details();
if (json.has(VideoID)) {
Log.d("has values", json.getString(VideoID));
}
video.setId(json.getString(ID));
video.setV_id(json.getString(VideoID));
video.setTitle(json.getString(Title));
video.setThumb(json.getString(VideoID));
videodetails.add(video);
if (json.has(VideoID))
{
Log.d("Video",VideoID);
}
}
} catch (Exception e) {
e.printStackTrace();
}
//Finally initializing our adapter
adapter = new DataAdapter(videodetails, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
}
MyAdapter
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<Video_Details> video;
public DataAdapter(List<Video_Details> video, Context context) {
super();
this.context = context;
this.video = video;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_row, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Video_Details videoDetails = video.get(position);
String url;
final String VideoID;
holder.title.setText(video.get(position).getTitle());
VideoID= video.get(position).getV_id();
url = video.get(position).getThumb();
Glide.with(context)
.load(url)
.override(150,70)
.into(holder.thumb);
//viewHolder.thumb.setText(android.get(i).getVer());
// viewHolder.tv_api_level.setText(android.get(i).getApi());
holder.vm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "You Clicked"+video.get(position).getV_id(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(),Play_Video.class);
intent.putExtra("VideoId",(video.get(position).getV_id()));
intent.putExtra("Title",(video.get(position).getTitle()));
v.getContext().startActivity(intent);
}
}
);
}
#Override
public int getItemCount() {
return video.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView thumb;
public String videoid;
public View vm;
public ViewHolder(View view) {
super(view);
vm = view;
title = (TextView)view.findViewById(R.id.title);
thumb = (ImageView) view.findViewById(R.id.thumb);
//tv_version = (TextView)view.findViewById(R.id.tv_version);
//tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);
}
}
}
Im currently making an app that takes movie name as input from user, after that input a new screen will be displayed showing list items of movie, the list of that movie is shown from "http://www.omdbapi.com/" just like IMDB. On clicking any list item(movie name) details of that movie will be shown in another screen, everything was working fine before getting input, I hard code the movie name before but now i want user to give inout but I think there's a problem in Edit Text I'm unable to get input from user.
MainActivity Class
public class MainActivity extends AppCompatActivity {
private static String LOG_TAG = MainActivity.class.getSimpleName();
private EditText editText;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateInput();
}
});
}
private void validateInput() {
String input = editText.getText().toString();
if (input != null || !input.equals("")) {
Intent intent = new Intent(this, MovieFragment.class);
intent.putExtra(Intent.EXTRA_TEXT, input);
startActivity(intent);
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
MovieFragment Class
public class MovieFragment extends Fragment implements OnNetworkCallHandled, RecyclerViewAdapter.OnClickListener {
private String movieName;
private Button button;
private RecyclerViewAdapter adapter;
private RecyclerView recyclerView;
private EditText editText;
private DataWrapper list;
public MovieFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
movieName = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text)).setText(movieName);
}
getMovieDetails();
return rootView;
}
private void getMovieDetails() {
MovieTask movieAsyncTask = new MovieTask(this, movieName);
movieAsyncTask.execute();
}
#Override
public void onNetworkcallSuccess(Object object) {
System.out.println("On success");
String result = (String) object;
Gson gson = new Gson();
list = gson.fromJson(result, DataWrapper.class);
adapter = new RecyclerViewAdapter(list.getSearch(), getContext(), this);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
System.out.println("On success");
}
#Override
public void onNetworkcallFailure(Object object) {
System.out.println("On failure");
}
#Override
public void onClick(View view, int position, long itemId) {
startActivity(position);
System.out.println();
}
private void startActivity(int position) {
Intent intent = new Intent(getActivity(), DetailActivity.class);
Bundle extras = new Bundle();
extras.putString("Title",list.getSearch().get(position).getTitle());
extras.putString("Year", list.getSearch().get(position).getYear());
intent.putExtras(extras);
startActivity(intent);
}
}
DetailActivity Class
public class DetailActivity extends AppCompatActivity {
private TextView Title;
private TextView Year;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
Title = (TextView) findViewById(R.id.Title);
Year = (TextView) findViewById(R.id.Year);
if (intent != null) {
String title = extras.getString("Title");
String year=extras.getString("Year");
Title.setText(title);
Year.setText(year);
System.out.println();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
MovieTask extending AsyncTask Class
public class MovieTask extends AsyncTask<Void, Void, String> {
private String LOG_TAG = MovieTask.class.getSimpleName();
private String response = "";
private String movieName;
private OnNetworkCallHandled onNetworkCallHandled;
public MovieTask(OnNetworkCallHandled onNetworkCallHandled, String movieName) {
this.onNetworkCallHandled = onNetworkCallHandled;
this.movieName = movieName;
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String MovieJsonStr = null;
try {
final String MOVIE_BASE_URL = "http://www.omdbapi.com/?";
final String s = "s";
final String plot = "plot";
final String r = "r";
final String page = "page";
Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon()
.appendQueryParameter(s, movieName)
.appendQueryParameter(plot, "full")
.appendQueryParameter(r, "json")
.appendQueryParameter(page, "1")
.build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
response = buffer.toString();
} catch (Exception e) {
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null || !result.equals("")) {
onNetworkCallHandled.onNetworkcallSuccess(result);
} else {
onNetworkCallHandled.onNetworkcallFailure(true);
}
}
}
RecyclerViewAdapter class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MovieDetailsHolder> {
private ArrayList<MovieDetails> movieDetails;
private Context context;
private OnClickListener onClick;
RecyclerViewAdapter(ArrayList<MovieDetails> movieDetails, Context context, OnClickListener onClick) {
this.onClick = onClick;
this.movieDetails = movieDetails;
this.context = context;
}
#Override
public MovieDetailsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);
return new MovieDetailsHolder(view);
}
#Override
public void onBindViewHolder(MovieDetailsHolder holder, final int position) {
holder.tVMovieName.setText(movieDetails.get(position).getTitle());
Picasso
.with(context)
.load(movieDetails.get(position).getPoster())
.into(holder.iVPoster);
holder.setOnClickListener(onClick);
}
#Override
public int getItemCount() {
return movieDetails.size();
}
public static class MovieDetailsHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private OnClickListener onClickListener;
CardView cv;
TextView tVMovieName;
ImageView iVPoster;
MovieDetailsHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cardView);
tVMovieName = (TextView) itemView.findViewById(R.id.tVMovieName);
iVPoster = (ImageView) itemView.findViewById(R.id.iVPoster);
itemView.setOnClickListener(this);
}
public void setOnClickListener(OnClickListener onClickListener) {
this.onClickListener = onClickListener;
}
#Override
public void onClick(View v) {
onClickListener.onClick(v, getPosition(), getItemId());
}
}
public interface OnClickListener {
public void onClick(View view, int position, long itemId);
}
}
You are treating MovieFragment as an activity
Intent intent = new Intent(this, MovieFragment.class);
intent.putExtra(Intent.EXTRA_TEXT, input);
startActivity(intent);
But MovieFragment is a fragment. You need to add/replace the MovieFragment in your activity.
Also, there is no need to setContentView(R.layout.activity_main); again in validateInput()
From a JSON array that I am parsing, I want to send a particular object value (using intent putExtra) to another activity. I have read this this question
and the accepted answer but I don't want to send all the values, in my case I only want to send the news_id as an integer to NewsDetails.class.
And I tried using the accepted answer to do it but I got stuck.
MainActivity
public class MainActivity extends AppCompatActivity{
private final String TAG = "MainActivity";
//Creating a list of newss
private List<NewsItems> mNewsItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.news_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the newslist
mNewsItemsList = new ArrayList<>();
adapter = new NewsAdapter(mNewsItemsList, this);
recyclerView.setAdapter(adapter);
//Caling method to get data
getData();
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Showing progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_news));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
/*progressDialog.dismiss();*/
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
NewsItems newsItem = new NewsItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
newsItem.setNews_title(jsonObject.getString(ConfigNews.TAG_NEWS_TITLE));
newsItem.setNews_excerpt(jsonObject.getString(ConfigNews.TAG_NEWS_EXCERPT));
newsItem.setNewsId(jsonObject.getInt(ConfigNews.TAG_NEWS_ID));
} catch (JSONException w) {
w.printStackTrace();
}
mNewsItemsList.add(newsItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
NewsItems class
public class NewsItems {
private String news_title;
private String news_excerpt;
private int news_id;
public String getNews_title() {
return news_title;
}
public void setNews_title(String news_title) {
this.news_title = news_title;
}
public String getNews_excerpt() {
return news_excerpt;
}
public void setNews_excerpt(String news_excerpt) {
this.news_excerpt = news_excerpt;
}
public int getNews_id() {
return news_id;
}
public void setNews_id(int news_id) {
this.news_id = news_id;
}
}
NewsAdapter
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private ImageLoader imageLoader;
private Context mContext;
//List of newss
private List<NewsItems> mNewsItems;
private final int VIEW_ITEM = 0;
private final int VIEW_PROG = 1;
private int lastPosition = -1;
public NewsAdapter(List<NewsItems> newsItems, Context context) {
super();
//Getting all newss
this.mNewsItems = newsItems;
this.mContext = context;
}
#Override
public int getItemViewType(int position) {
if (isPositionItem(position))
return VIEW_ITEM;
return VIEW_PROG;
}
private boolean isPositionItem(int position) {
return position != getItemCount()-1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_summ, parent, false);
return new TextViewHolder(v, mContext);
} else if (viewType == VIEW_PROG){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerfooter, parent, false);
return new ProgressViewHolder(v);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
#Override
public int getItemCount(){
//Return the number of items in the data set
return mNewsItems.size();
}
public static class TextViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView newsTitle,newsExcerpt, newsId;
public ImageButton imageButton;
public NewsItems dNewsItems;
private Context context;
public TextViewHolder (final View newsView, final Context context) {
super(newsView);
this.context = context;
newsTitle = (TextView) newsView.findViewById(R.id.news_title);
newsExcerpt = (TextView) newsView.findViewById(R.id.news_excerpt);
newsId = (TextView) newsView.findViewById(R.id.news_id);
newsExcerpt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("PostId", //This is where I got confused);
}
}
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
Button loadButton;
ProgressBar progressBar;
public ProgressViewHolder(View footerView){
super(footerView);
loadButton = (Button) footerView.findViewById(R.id.reload_button);
progressBar = (ProgressBar) footerView.findViewById(R.id.progress_load);
loadButton.setOnClickListener(this);
if(NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
progressBar.setVisibility(View.VISIBLE);
} else if (!NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
loadButton.setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
if (v.getId() == loadButton.getId()) {
//
}
}
}
}
You can send single value also instead of complete object like this -
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",<your_news_id_here>);
startActivity(intent);
}
}
}
In your case, remove onClick(View v) and change your onBindViewHolder() to setOnClickListener() on newsExcerpt like this -
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
((TextViewHolder) holder).newsExcerpt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",newsList.getNewsId()); //Any getter of your class you want
startActivity(intent);
});
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
I don't want to send all the values
You dont' have to send all, It's up to you and your needs.
Intent i = new Intent(context, DestActivity.class);
i.putExtra(KEY_NEWS_ID, news_id );
On the other end:
int news_id = getIntent().getIntExtra(KEY_NEWS_ID, defaultValue);