converting class into interface - java

please help me about that how i can convert my class into interface so other classes can use main menu . or let me know if there is easy way to call the same menu in the main class except extends bcz there are classes which already are extending other classes. here is the sample code
package com.droidnova.android.howto.optionmenu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class ControlMenu extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, ShowSettings.class);
startActivity(intent);
break;
case R.id.services:
Intent intent2 = new Intent(this, Test.class);
startActivity(intent2);
break;
case R.id.Quit:
finish();
break;
default:
break;
}
return true;
}
}
i want to call these menus into other classes (one of them are listed below) so that option menu is available on every activity without using extends.
public class Test extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php");
try{
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("name"));
map.put("password", "Magnitude: " + e.getString("password"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
now i am following this way
package com.droidnova.android.howto.optionmenu;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
public class MenuHandler extends Activity{
private Activity activity;
public MenuHandler(Activity activity) {
this.activity = activity;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, ShowSettings.class);
startActivity(intent);
break;
case R.id.services:
Intent intent2 = new Intent(this, Test.class);
startActivity(intent2);
break;
case R.id.Quit:
finish();
break;
default:
break;
}
return true;
}
}
and Test class is
package com.droidnova.android.howto.optionmenu;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Test extends ListActivity {
private MenuHandler menuHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
menuHandler = new MenuHandler(this);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php");
try{
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("name"));
map.put("password", "Magnitude: " + e.getString("password"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return menuHandler.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return menuHandler.onOptionsItemSelected(item);
}
}
menu are perfectly appearing on the screen but when i am clicking on any menu it "Force to stop" pops up
Now i am able to get logat errors Here they are

What I would do is create a special class to handle menu creation and events and delegate everythng to it. The code will look like this:
public class MenuHandler {
private Activity activity;
public MenuHandler(Activity activity) {
this.activity = activity;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
//Handle events here
}
}
Then when you need to have a menu in your Activity, you create MenuHandler and delegate method calls to it:
public MyActivity extends Activity {
private MenuHandler menuHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
menuHandler = new MenuHandler(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return menuHandler.onCreateOprionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return menuHandler.onOptionsItemSelected(item);
}
}

An interface does not have an implementation, so I don't think that will do what you want.
What you can do is make an activity that extends your ControlMenu. It will be an Activity (because controlmenu itself extends activity), and it will be able to use the code you have provided here. It will look something like
public class yourActivity extends ControlMenu{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //oncreate of controlmenu
LayoutInflater inflater = getLayoutInflater();
RelativeLayout ll = (RelativeLayout) findViewById(R.id.main);
ListView lv = (ListView) inflater.inflate(R.layout.yourlistview, ll, false);
ll.addView(lv);
lv.setAdapter(new YourAdapter(this));
}
}
and you'll have an adapter that goes like (quick mock-up)
public abstract class YourAdapter extends BaseAdapter {
final public int getCount() {}
final public Object getItem(int position) {}
final public long getItemId(int position) {}
final public void onItemClick() {}
}

Related

Listview selected item highlight coming from database?

I am beginner in android creating religious book I have two activities both have listview the data is coming from sqlite database when i click any particular item from first activity switch to second activity show all detail in second activity which also have listview my question how to highlight second list item row only particular item is highlighted ! here example shown in picture what actually i want
here if anyone click on verse 13 all verse 1-25 is all show but only highlight verse 13 in next activity how this can be done here is my code
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Chapters extends AppCompatActivity {
private ListView listView;
private ArrayList<String> stringArrayList;
private ArrayAdapter<String> adapter;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private String bookname;
TextView setbookname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapters);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setbookname=(TextView)findViewById(R.id.bookname);
Intent mIntent = getIntent();
booknumber= mIntent.getIntExtra("booknumber", 0);
bookname=mIntent.getStringExtra("bookname");
setbookname.setText(bookname);
toolbar.setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Toast.makeText(this, ""+booknumber, Toast.LENGTH_SHORT).show();
setData();
listView =findViewById(R.id.list);
adapter = new ChapterAdopter(Chapters.this, R.layout.item_listview, stringArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int chapternumber=position+1;
Toast.makeText(Chapters.this, ""+chapternumber, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Chapters.this,Verse.class);
intent.putExtra("Booknumber",booknumber);
intent.putExtra("Chapternumber",chapternumber);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.chapter,menu);
MenuItem menuItem=menu.findItem(R.id.chapter_search);
SearchView searchView=(SearchView)menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void setData() {
stringArrayList = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select DISTINCT c from t_asv where b="+booknumber, new String[]{});
if(cursor!=null && cursor.getCount() > 0)
{
if (cursor.moveToFirst())
{
do {
stringArrayList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
}
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class Verse extends AppCompatActivity {
private ListView listView;
private ArrayList<String> stringArrayList;
private ArrayAdapter<String> adapter;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private int chapternumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verse);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Intent mIntent = getIntent();
booknumber = mIntent.getIntExtra("Booknumber", 0);
chapternumber= mIntent.getIntExtra("Chapternumber", 0);
toolbar.setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
setData();
listView = findViewById(R.id.list);
adapter = new VerseAdopter(Verse.this, R.layout.item_listview, stringArrayList);
Toast.makeText(this, ""+booknumber, Toast.LENGTH_SHORT).show();
listView.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.chapter, menu);
MenuItem menuItem = menu.findItem(R.id.chapter_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void setData() {
stringArrayList = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select v FROM t_asv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
stringArrayList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
}
It appears that you are passing the selected verse as a chapter and then in the query Cursor cursor = mDb.rawQuery("select v FROM t_asv where b="+booknumber+" AND c="+chapternumber+";", new String[]{}); therefore selecting all verses from the passed book/chapter.
You perhaps need to pass the clicked value as the verse as well as the book and chapter and use a query that includes the verse in the WHERE clause, perhaps cursor = mDb.rawQuery("select v FROM t_asv where b="+booknumber+" AND c="+chapternumber+" AND v=" + versenumber + " ;", new String[]{});

Scrape web's infinite scrolling “load more” button using Java in Android Studio

So far I can't find an article that explains how to handle scraping infinite scrolling page in Android Studio's Java. Maybe I'm not good at searching or else.
I'm doing a news app project that will display news using web scraping technique, and can also fetch data from the next page.
More on here : How to crawl a website with multiple pages using java
But, now I'm facing a new problem because one of my news source using infinite scrolling method for their site -> https://www.gameinformer.com/news
So, is there any way I can fetch the news data from this website's load more button ?
In case anyone need my code, here it is :
GameInformer's main activity :
package com.example.user.newsapp;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class News_GameInformer extends AppCompatActivity {
Toolbar toolbar;
private ProgressDialog mProgressDialog;
private String url = "https://www.gameinformer.com/news";
private ArrayList<String> mNewsTitleList = new ArrayList<>();
private ArrayList<String> mNewsDescList = new ArrayList<>();
private ArrayList<String> mNewsDateList = new ArrayList<>();
private CardView cardView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news__game_informer);
new Description().execute();
toolbar = findViewById(R.id.toolbar_news_gameinformer);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private class Description extends AsyncTask<Void,Void,Void> {
String desc;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(News_GameInformer.this);
mProgressDialog.setTitle("Connecting to GameInformer.com");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document mNewsDocument = Jsoup.connect(url).get();
Elements mElementDataSize = mNewsDocument.select("article[class=node teaser node--type-article node--promoted node--view-mode-teaser]");
int mElementSize = mElementDataSize.size();
for (int i=0;i<mElementSize;i++) {
Elements mElementNewsTitle = mNewsDocument.select("h2[class=page-title]").select("span").eq(i);
String mNewsTitle = mElementNewsTitle.text();
Elements mElementNewsDesc = mNewsDocument.select("div[class=field field--name-field-promo-summary field--type-string field--label-hidden field__item]").eq(i);
String mNewsDesc = mElementNewsDesc.text();
Elements mElementNewsDate = mNewsDocument.select("div[class=node__submitted author-details]").select("span[class=field field--name-created field--type-created field--label-hidden]").eq(i);
String mNewsDate = mElementNewsDate.text();
mNewsTitleList.add(mNewsTitle);
mNewsDescList.add(mNewsDesc);
mNewsDateList.add(mNewsDate);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
RecyclerView mRecyclerView = findViewById(R.id.act_recyclerview_gi_news);
gameinformer_DataAdapter mDataAdapter = new gameinformer_DataAdapter(News_GameInformer.this, mNewsTitleList, mNewsDescList, mNewsDateList, cardView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mDataAdapter);
mProgressDialog.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.gamezone) {
Intent i = new Intent(getApplicationContext(),News_GameZone.class);
startActivity(i);
} else if (id==R.id.gameinformer) {
Intent i = new Intent(getApplicationContext(),News_GameInformer.class);
startActivity(i);
} else if (id==R.id.gamespot) {
Intent i = new Intent(getApplicationContext(),News_GameSpot.class);
startActivity(i);
} else if (id==R.id.pcgamer) {
Intent i = new Intent(getApplicationContext(),News_PCGamer.class);
startActivity(i);
} else if (id==android.R.id.home) {
finish();
} else if (id==R.id.menuinfo) {
Intent i = new Intent(getApplicationContext(),Info.class);
startActivity(i);
} else if (id==R.id.menupeople) {
Intent i = new Intent(getApplicationContext(),People.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Data Adapter's code :
package com.example.user.newsapp;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class gameinformer_DataAdapter extends RecyclerView.Adapter<gameinformer_DataAdapter.MyViewHolder> {
private ArrayList<String> mNewsTitleList = new ArrayList<>();
private ArrayList<String> mNewsDescList = new ArrayList<>();
private ArrayList<String> mNewsDateList = new ArrayList<>();
private Activity mActivity;
private int lastPosition=-1;
private CardView cardView;
public gameinformer_DataAdapter (News_GameInformer activity, ArrayList<String> mNewsTitleList, ArrayList<String> mNewsDescList, ArrayList<String> mNewsDateList, CardView cardView) {
this.mActivity = activity;
this.mNewsTitleList = mNewsTitleList;
this.mNewsDescList = mNewsDescList;
this.mNewsDateList = mNewsDateList;
this.cardView = cardView;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView gameinformer_news_title, gameinformer_news_desc, gameinformer_news_date;
private CardView cardView_layout;
public MyViewHolder(View view) {
super(view);
gameinformer_news_title = view.findViewById(R.id.row_gi_news_title);
gameinformer_news_desc = view.findViewById(R.id.row_gi_news_desc);
gameinformer_news_date = view.findViewById(R.id.row_gi_news_date);
cardView_layout = view.findViewById(R.id.gi_cardview);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gameinformer_row_data,parent,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.gameinformer_news_title.setText(mNewsTitleList.get(position));
holder.gameinformer_news_desc.setText(mNewsDescList.get(position));
holder.gameinformer_news_date.setText(mNewsDateList.get(position));
holder.cardView_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = mNewsTitleList.get(position);
Intent i = new Intent(mActivity, News_GameInformer_Webview.class);
i.putExtra("keytitle",title);
mActivity.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mNewsTitleList.size();
}
}

How to pass an arraylist to a fragment from adapter?

Actually, I am adding objects in ArrayList from a RecyclerAdapter and I have written a function for getting the arraylist in adapter.And I am getting the arraylist from that function in MainActivity.But whenever I am trying to pass that arraylist from MainActivity to a Fragment it is giving NullPointer(Null value).
Help me.
package com.example.codingmounrtain.addtocartbadgecount.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.codingmounrtain.addtocartbadgecount.activity.MainActivity;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
ArrayList<Movie> cartmovies = new ArrayList<>();
public interface Listener {
void onSelectMovie(int position);
}
Context context;
private final ArrayList<Movie> movies;
private final Listener listener;
public RecyclerAdapter(Context context, ArrayList<Movie> movies,Listener listener) {
this.context = context;
this.movies = movies;
this.listener = listener;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.productName.setText(movies.get(position).getTitle());
Picasso.with(context).load(movies.get(position).getPhoto()).centerCrop().resize(400,400).into(holder.productImage);
holder.productImage.setImageResource(movies.get(position).getPhoto());
holder.productImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onSelectMovie(position);
}
});
holder.addRemoveBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!movies.get(position).isAddedTocart())
{
Log.v("tej","tej");
movies.get(position).setAddedTocart(true);
Log.v("t","t");
holder.addRemoveBt.setText("Remove");
Movie movie = movies.get(position);
cartmovies.add(movie);
Log.v("t","t");
if(context instanceof MainActivity)
{
((AddorRemoveCallbacks)context).onAddProduct();
}
}
else
{
movies.get(position).setAddedTocart(false);
Movie movie = movies.get(position);
cartmovies.remove(movie);
holder.addRemoveBt.setText("Add");
((AddorRemoveCallbacks)context).onRemoveProduct();
}
}
});
}
public ArrayList<Movie> getArrayList(){
return cartmovies;
}
#Override
public int getItemCount() {
return movies.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView productImage;
TextView productName;
Button addRemoveBt;
public MyViewHolder(View itemView) {
super(itemView);
productImage=(ImageView) itemView.findViewById(R.id.productImageView);
productName=(TextView) itemView.findViewById(R.id.productNameTv);
addRemoveBt=(Button)itemView.findViewById(R.id.addButton);
}
}
}
MainActivity.java
package com.example.codingmounrtain.addtocartbadgecount.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.example.codingmounrtain.addtocartbadgecount.Converter;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
import com.example.codingmounrtain.addtocartbadgecount.fragment.CartFragment;
import com.example.codingmounrtain.addtocartbadgecount.fragment.SearchFragment;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;
import java.util.ArrayList;
import java.util.Iterator;
public class MainActivity extends AppCompatActivity implements AddorRemoveCallbacks,RecyclerAdapter.Listener{
ArrayList<Movie> cartmovies = new ArrayList<>();
ArrayList<Movie> movies = new ArrayList<>();
RecyclerView mRecyclerView;
RecyclerAdapter mAdapter;
private static int cart_count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("MovieShop");
getSupportActionBar().show();
movies.add(new Movie("Stree","A town is held in the grip of terror by tales of a mysterious woman who calls men by their name and then abducts them, leaving their clothes behind.","Rajkummar Rao","Shraddha Kapoor","Amar Kaushik",4.0f,R.drawable.stree));
movies.add(new Movie("Nun","When a young nun at a cloistered abbey in Romania takes her own life, a priest with a haunted past and a novitiate on the threshold of her final vows are sent by the Vatican to investigate. ","Demián Bichir","Taissa Farmiga","Corin Hardy",2.5f,R.drawable.nun));
movies.add(new Movie("Savita Damodar Paranjpe","The lives of a married couple are turned upside down when hard truths come to light.","Subodh Bhave","Trupti Madhukar Toradmal","Swapna Waghmare Joshi",3.5f,R.drawable.savita));
movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));
movies.add(new Movie("MI","Ethan Hunt and the IMF team join forces with CIA assassin August Walker to prevent a disaster of epic proportions.","Tom Cruise","Rebecca Ferguson","Christopher McQuarrie",4.0f,R.drawable.mi));
movies.add(new Movie("Searching","After David Kim (John Cho)'s 16-year-old daughter goes missing, a local investigation is opened and a detective is assigned to the case. ","John Cho","Debra Messing","Aneesh Chaganty",2.5f,R.drawable.searching));
movies.add(new Movie("SURYA"," Indian Telugu-language action film written and directed by Vakkantham Vamsi in his directorial debut. ","Allu Arjun","Anu Emmanuel","Vakkantham Vamsi",3.5f,R.drawable.surya));
movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
GridLayoutManager mLayoutManager = new GridLayoutManager(this,2);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new RecyclerAdapter(this, movies,this);
mRecyclerView.setAdapter(mAdapter);
}
#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);
MenuItem menuItem = menu.findItem(R.id.cart_action);
menuItem.setIcon(Converter.convertLayoutToImage(MainActivity.this,cart_count,R.drawable.ic_shopping_cart_white_24dp));
MenuItem menuItem2 = menu.findItem(R.id.search_action);
menuItem2.setIcon(R.drawable.ic_search_black_24dp);
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();
cartmovies = mAdapter.getArrayList();
Movie movie = null;
Iterator<Movie> iter = cartmovies.iterator();
while ( iter .hasNext() == true )
{
movie = iter.next();
Log.v("tejjjj",movie.getTitle());
}
// cartmovies.get(0).getTitle();
if(id==R.id.cart_action){
Bundle bundle = new Bundle();
bundle.putSerializable("catmovies",cartmovies);
Fragment fragment = new CartFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.contentLayout, fragment)
.addToBackStack("MainActivity")
.commit();
}
if(id==R.id.search_action){
Bundle bundle = new Bundle();
// bundle.putString("query", editSearch.getText().toString());
bundle.putSerializable("movies",movies);
Fragment fragment = new SearchFragment();
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.contentLayout, fragment)
.addToBackStack("MainActivity")
.commit();
// search(searchStr, movies);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAddProduct() {
cart_count++;
Log.v("stej",""+cart_count);
invalidateOptionsMenu();
Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie added to cart !!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
#Override
public void onRemoveProduct() {
cart_count--;
Log.v("tej",""+cart_count);
invalidateOptionsMenu();
Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie removed from cart !!", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
#Override
public void onSelectMovie(int position) {
Movie movie = movies.get(position);
// Toast.makeText(this, "selected movie: " + movie.getTitle(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("title",movie.getTitle());
intent.putExtra("director",movie.getDirector());
intent.putExtra("actors",movie.getActors());
intent.putExtra("actresses",movie.getActresses());
intent.putExtra("info",movie.getDescription());
intent.putExtra("photo",movie.getPhoto());
intent.putExtra("rating",movie.getRating());
startActivity(intent);
}
}
CartFragment.java
package com.example.codingmounrtain.addtocartbadgecount.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.activity.DetailActivity;
import com.example.codingmounrtain.addtocartbadgecount.adapter.MovieListAdapter;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
import java.util.ArrayList;
import java.util.Iterator;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
public class CartFragment extends Fragment implements View.OnClickListener, MovieListAdapter.Listener {
#BindView(R.id.recyclerView)
RecyclerView recyclerView;
Unbinder unbinder;
MovieListAdapter adapter;
RecyclerAdapter madapter;
ArrayList<Movie> movies = new ArrayList<>();
ArrayList<Movie> movies1 = new ArrayList<>();
public CartFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.fragment_cart, null);
unbinder = ButterKnife.bind(this, layout);
adapter = new MovieListAdapter(getActivity(),movies,this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Movie Cart");
// movies1 =(ArrayList<Movie>) savedInstanceState.getParcelable("movies");
// buttonSearch.setOnClickListener(this);
return layout;
}
#Override
public void onResume() {
super.onResume();
getList();
}
#Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
void getList(){
Bundle bundle = getArguments();
movies1 =(ArrayList<Movie>) bundle.getSerializable("cartmovies");
Iterator<Movie> iter = movies1.iterator();
Movie movie = null;
while(iter.hasNext() == true){
movie = iter.next();
movies.add(movie);
adapter.notifyDataSetChanged();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onSelectMovie(int position) {
Movie movie = movies.get(position);
Intent intent = new Intent(getActivity(),DetailActivity.class);
intent.putExtra("title",movie.getTitle());
intent.putExtra("director",movie.getDirector());
intent.putExtra("actors",movie.getActors());
intent.putExtra("actresses",movie.getActresses());
intent.putExtra("info",movie.getDescription());
intent.putExtra("photo",movie.getPhoto());
intent.putExtra("rating",movie.getRating());
startActivity(intent);
}
}
Write a get method inside your adapter then call it from your activity or fragment.
public ArrayList<Object> getArrayList() {
return yourArrayList;
}
Inside your activity you can get this like, yourAdapterObject.getArrayList();
Try to pass it via bundle.
First create a model class which will be passed. It should implement Serializable
public class MyModel implements Serializable {
private ArrayList<Data> datas;
public MyModel(ArrayList<Data> datas) {
this.datas = datas
}
}
Then put your data to the bundle
Bundle bundle = new Bundle();
bundle.putSerializable();
Finally put that bundle instance to your fragment
myFragment.setArguments(bundle);
You can pass your array list to fragment by setting arguments for that fragment. But for that, the type of object your array list contains should extend Serializable. Then make a getInstance() method in your fragment that returns an instance of your fragment and wherever you are opening your fragment call that getInstance() method and pass your Array list.
getSupportFragmentManager().beginTransaction()
.add(containerId, YourFragment.getInstance(yourArrayList), tag)
.commitAllowingStateLoss();
The sample code snippet for getInstance() method in your fragment is:
public static YourFragment getInstance( ArrayList<Object> yourArrayList) {
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(Constants.YOUR_LIST,yourArrayList);
YourFragment yourFragment = new YourFragment();
yourFragment.setArguments(bundle);
return yourFragment;
}
Now, you can get your arraylist by calling getArguments() wherever need in your fragment. Also, make sure to check for null Arguments. The sample code for this is:
if (getArguments()!=null && getArguments().containsKey(Constants.YOUR_LIST) && getArguments().getParcelableArrayList(Constants.YOUR_LIST) != null){
ArrayList<Object> yourlist = getArguments().getParcelableArrayList(Constants.YOUR_LIST);
}
Now, by making this list global you can access it anywhere in the fragment. Hope, it helps.

I have two activity.When i was click on first activity list view,second activity open. number of count in first activity also increase

I have two activities. When I clicked on first activity in list view, second activity opened .Second activity have one button number of item. when I clicked on second activity number of count goes to first activity. It is repeated process but number of count in first activity also gets increased.
My first activity..
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.adapter.ListAdapterAddItems;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DetaisRESTActivity extends Activity {
String messagevaluename,totalamount,valueid,valueid1,valuename,pos;
public String countString=null;
public int count=0;
public String message=null;
public static String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
String restaurantmenuname,rastaurantname;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
public static String RASTAURANTNAMEDETAILS = "RestaurantPizzaItemName";
public static String RASTAURANTRUPPEES = "RestaurantPizzaItemPrice";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_detais_rest);
// getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.titlebar);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
//listview.invalidateViews();
adapter.notifyDataSetChanged();
// listview.notifyAll();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
//count++;
//countString=String.valueOf(count);
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
//Toast.makeText(getBaseContext(),
// countString, Toast.LENGTH_LONG).show();
Log.i("postititi",""+position);
// mTitleTextView.setText(countString);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
// aa=new ArrayList();
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
//ruppees.setText(message);
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#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_detais_rest, 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.
return super.onOptionsItemSelected(item);
}
}
Second activity....
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String Name;
ImageButton positive,negative;
String position;
int count = 1;
int tot_amt = 0;
public String countString=null;
String Rs,name,price;
String valueid,valueid1,valuename;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
// value1 = intent.getStringExtra("numericitem");
// int numericvalue = intent.getIntExtra("numericitem", 11);
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getString =quantity.getText().toString();
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getString =quantity.getText().toString();
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
if (count > 1)
count--;
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
setResult(2,intent);
finish();//finishing activity
}
});
}
#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_quentity, 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);
}
}

Menu buttons work, Soft buttons not working. Same Code basically

Title says it all, Im new to SQL and trying to change the selection the user makes but placing buttons in the screen and not use the MENU button. Seems like the buttons aren't instantiated but the code looks right to me...what am i missing??
package com.example.worldcountriesbooks;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ViewCountry extends Activity implements OnClickListener{
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView newEt;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
Button a = (Button)findViewById(R.id.editbutton);
Button b = (Button)findViewById(R.id.deletebutton);
a.setOnClickListener(this);
b.setOnClickListener(this); //Set them up right here...
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
codeTv = (TextView) findViewById(R.id.codeText);
newEt = (TextView)findViewById(R.id.newText);
}
#Override
protected void onResume()
{
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor>
{
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params)
{
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result)
{
super.onPostExecute(result);
result.moveToFirst();
// get the column index for each data item
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int newIndex = result.getColumnIndex("newb");
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
codeTv.setText(result.getString(codeIndex));
newEt.setText(result.getString(newIndex));
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.editItem:
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
addEditContact.putExtra("newb", newEt.getText());
startActivity(addEditContact);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact()
{
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int button)
{
final DatabaseConnector dbConnector =
new DatabaseConnector(ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask =
new AsyncTask<Long, Object, Object>()
{
#Override
protected Object doInBackground(Long... params)
{
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
}
);
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
public void onClick(View arg0) {
switch (arg0.getId())
{
case R.id.editItem:
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
addEditContact.putExtra("newb", newEt.getText());
startActivity(addEditContact);
break;
case R.id.deleteItem:
deleteContact();
break;//finish them up here and they do nothing...
}
}
}
Now the menu buttons work great so not sure whats up...Thanks for looking
The menu buttons work great because the switch statement for it is proper.
Your onClick is not working properly however. This is because The cases are for different ids than what the buttons provide. You want R.id.editbutton and R.id.deletebutton instead.
Your method should look like:
public void onClick(View arg0) {
switch (arg0.getId())
{
case R.id.editbutton: //updated
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
addEditContact.putExtra("newb", newEt.getText());
startActivity(addEditContact);
break;
case R.id.deletebutton: //updated
deleteContact();
break;
}
}
}

Categories