so I have these code
main.java
package com.example.kamusinggris_indonesiaidiom;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity {
private TextView teks;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
teks = (TextView) findViewById(R.id.text);
list = (ListView) findViewById(R.id.list);
}
protected void onNewIntent(Intent intent) {
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
// TODO Auto-generated method stub
handleIntent(intent);
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Intent wordIntent = new Intent(this, Definisi.class);
wordIntent.setData(intent.getData());
startActivity(wordIntent);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
// TODO Auto-generated method stub
Cursor cursor = managedQuery(Provider.CONTENT_URI, null, null,
new String[] {query}, null);
if (cursor == null) {
// There are no results
teks.setText(getString(R.string.no_results, new Object[] {query}));
} else {
// Display the number of results
int count = cursor.getCount();
String countString = getResources().getQuantityString(R.plurals.search_results,
count, new Object[] {count, query});
teks.setText(countString);
// Specify the columns we want to display in the result
String[] from = new String[] { Database.KATA,
Database.DEFINISI };
// Specify the corresponding layout elements where we want the columns to go
int[] to = new int[] { R.id.kata,
R.id.definisi };
// Create a simple cursor adapter for the definitions and apply them to the ListView
SimpleCursorAdapter words = new SimpleCursorAdapter(this,
R.layout.hasil_pencarian, cursor, from, to);
list.setAdapter(words);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View tmp,
int posisi, long id) {
// TODO Auto-generated method stub
Intent definisi = new Intent(getApplicationContext(), Definisi.class);
Uri data = Uri.withAppendedPath(Provider.CONTENT_URI,
String.valueOf(id));
definisi.setData(data);
startActivity(definisi);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()) );
searchView.setIconifiedByDefault(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
default:
return false;
}
}
}
definisi.java
package com.example.kamusinggris_indonesiaidiom;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.TextView;
public class Definisi extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definisi);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
Uri uri = getIntent().getData();
Cursor kursor = managedQuery(uri, null, null, null, null);
if (kursor == null) {
finish();
} else {
kursor.moveToFirst();
TextView kata = (TextView) findViewById(R.id.kata);
TextView definisi= (TextView) findViewById(R.id.definisi);
int wIndex = kursor.getColumnIndexOrThrow(Database.KATA);
int dIndex = kursor.getColumnIndexOrThrow(Database.DEFINISI);
kata.setText(kursor.getString(wIndex));
definisi.setText(kursor.getString(dIndex));
} }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
case android.R.id.home:
Intent a = new Intent(this, Main.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
return true;
default:
return false;
}
}
}
its a dictionary, so when a search suggestion on a listview is clicked, it supposed to open the definisi.java and display the definition. But what I got here is when I clicked the search suggestion it displayed the main.java (its just go back to the previous activity). what's wrong on the intent part? please help me
Use passed intent variable in onNewIntent
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
You should also remove call to handleIntent from within handleIntent method
Related
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[]{});
When I add a header to my listview it messes up my onclick,it selects the wrong item every time.
package ie.example.artur.projectrepeat;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DataListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView listView;
SQLiteDatabase sqLiteDatabase;
DatabaseClass database;
Cursor cursor;
ListDataAdapter listDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_list_layout);
listView = (ListView) findViewById(R.id.list_view);
listDataAdapter = new ListDataAdapter(getApplicationContext(), R.layout.row_layout);
listView.setAdapter(listDataAdapter);
listView.setOnItemClickListener(this);
database = new DatabaseClass(getApplicationContext());
sqLiteDatabase = database.getReadableDatabase();
Cursor cursor=database.getInformation(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String id, product_name, category,quantity,importance;
id = cursor.getString(0);
product_name = cursor.getString(1);
category = cursor.getString(2);
quantity = cursor.getString(3);
importance = cursor.getString(4);
DataProvider dataProvider = new DataProvider(id, product_name, category,quantity,importance);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
}
#Override
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
final TextView tv = (TextView) view.findViewById(R.id.product_id);
AlertDialog.Builder alert = new AlertDialog.Builder(
DataListActivity.this);
alert.setTitle("Alert!!");
alert.setMessage("Are you sure to delete record");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do your work here
sqLiteDatabase = database.getReadableDatabase();
DatabaseClass.DeleteInformation(tv.getText().toString(), sqLiteDatabase);
listView.setAdapter(listDataAdapter);
listDataAdapter.notifyDataSetChanged();
listDataAdapter.removeItemAt(position);
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.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.
{
switch (item.getItemId())
{
case R.id.home : startActivity (new Intent(this, Main2Activity.class));
break;
case R.id.action_settings : startActivity (new Intent(this, SecondActivity.class));
break;
case R.id.catalogue :startActivity (new Intent(this, ViewAllItems.class));
break;
case R.id.ViewList :startActivity (new Intent(this, DataListActivity.class));
break;
case R.id.find :startActivity (new Intent(this, Main3Activity.class));
break;
case R.id.Update :startActivity (new Intent(this, Edit_Activity.class));
break;
}
return super.onOptionsItemSelected(item);
}}
}
When I add this code it messes up my app:
LayoutInflater myinflater = getLayoutInflater();
ViewGroup myHeader = (ViewGroup)myinflater.inflate(R.layout.header, listView, false);
listView.addHeaderView(myHeader, null, false)
The reason for that is that the header counts as additional one item inside your listview so when click on item you get the item in position - 1.
Add this inside onItemClick:
position -= listView.getHeaderViewsCount(); // or position - 1
So I am trying to create a simple activity page that shows all contacts. Using the search view in the action bar, they should be able to filter the contacts. The contacts are correctly being populated into the ListView but the SearchView is not filtering the list. The list never updates.
This is my contacts activity:
package com.example.android.whereyouat;
import android.app.SearchManager;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.NavUtils;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
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.ListView;
import android.widget.SimpleCursorAdapter;
public class Contacts extends AppCompatActivity {
Cursor cursor1;
SimpleCursorAdapter adapter;
SearchView searchView;
ListView lv;
MenuItem searchMenuItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
lv = (ListView) findViewById(R.id.list);
cursor1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
startManagingCursor(cursor1);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1, android.R.id.text2};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor1, from, to);
lv.setAdapter(adapter);
lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE);
lv.setTextFilterEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_contacts, menu);
searchMenuItem = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
SearchManager SManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
android.support.v7.widget.SearchView searchViewAction = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(searchMenuItem);
searchViewAction.setSearchableInfo(SManager.getSearchableInfo(getComponentName()));
searchViewAction.setIconifiedByDefault(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.action_search:
//openSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
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);
}
}
i am trying to show some buttons in actionbar but they just dont show up
i have successfully implemented the navigation drawer and viewpager using fragments
the implementes for showing menu inflator and action bar buttons has also been done but they just wont show up
in menu/main.xml i have added app:showAsAction="always" but still it wont show up
here is the
detailactivity.java
package com.test.app;
import java.lang.reflect.Field;
import android.app.ActionBar;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
//import android.support.v7.app.ActionBar;
import com.Blog.gkgyan.parser.RSSFeed;
//public class DetailActivity extends FragmentActivity implements OnItemClickListener{
public class DetailActivity extends FragmentActivity implements OnItemClickListener{
RSSFeed feed;
int pos;
private DescAdapter adapter;
private ViewPager pager;
private DrawerLayout drawerLayout;
private ListView listView;
private String[] planets;
private ActionBarDrawerToggle drawerListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
//Drawer Layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerListener = new ActionBarDrawerToggle(this, drawerLayout,R.drawable.ic_drawer,R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
//super.onDrawerClosed(drawerView);
Toast.makeText(DetailActivity.this, "Drawer closed", Toast.LENGTH_LONG).show();
}
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
//super.onDrawerOpened(drawerView);
Toast.makeText(DetailActivity.this, "Drawer opened", Toast.LENGTH_LONG).show();
}
};
drawerLayout.setDrawerListener(drawerListener);
//getSupportActionBar().setHomeButtonEnabled(true);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);;
getActionBar().setDisplayHomeAsUpEnabled(true);
// try {
// ViewConfiguration config = ViewConfiguration.get(this);
// Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
// if (menuKeyField != null) {
// menuKeyField.setAccessible(true);
// menuKeyField.setBoolean(config, false);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) { e.printStackTrace(); }
}
listView = (ListView) findViewById(R.id.drawerlist);
planets = getResources().getStringArray(R.array.planets);
listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, planets ));
listView.setOnItemClickListener(this);
// Get the feed object and the position from the Intent
feed = (RSSFeed) getIntent().getExtras().get("feed");
pos = getIntent().getExtras().getInt("pos");
// Initialize the views
adapter = new DescAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
// Set Adapter to pager:
pager.setAdapter(adapter);
pager.setCurrentItem(pos);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
//return super.onCreateOptionsMenu(menu);
}
//#Override
//public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (drawerListener.onOptionsItemSelected(item)) {
return true;
}
Intent i = null;
switch (item.getItemId()) {
case R.id.action_rate:
String webpage = "http://developer.android.com/index.html";
i = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(i);
//return true;
break;
case R.id.action_share:
i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "Hello from Hansel and Petal!");
i.setType("text/plain");
startActivity(i);
//return true;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
drawerListener.syncState();
}
public class DescAdapter extends FragmentStatePagerAdapter {
public DescAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return feed.getItemCount();
}
#Override
public Fragment getItem(int position) {
DetailFragment frag = new DetailFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
bundle.putInt("pos", position);
frag.setArguments(bundle);
return frag;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
if (position == 0) {
Intent intent = new Intent(this, GkcategoryListActivity.class);
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(this, GkcategoryListActivity.class);
startActivity(intent);
}
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
`
and menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.Blog.gkgyan.MainActivity" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never"/>
<item
android:id="#+id/action_share"
android:icon="#drawable/ic_action_share"
android:orderInCategory="101"
android:title="#string/action_share"
app:showAsAction="always" />
<item
android:id="#+id/action_rate"
android:icon="#drawable/ic_action_important"
android:orderInCategory="101"
android:title="#string/action_rate"
app:showAsAction="always"/>
</menu>
i wan to show the action_share and Action_rate butons in action bar on detailactivity.java tried every thing nothing works on this page
however it does work perfectly fine in main activity.java
here is the code
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
Intent intent = null;
switch (item.getItemId()) {
case R.id.action_rate:
String webpage = "http://developer.android.com/index.html";
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent);
break;
case R.id.action_share:
intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello from Hansel and Petal!");
intent.setType("text/plain");
startActivity(intent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void latestActivity(View v){
//Intent intent = new Intent(this, SplashActivity.class);
Intent intent = new Intent(this, GkcategoryListActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
is it a issue with fragment activity or navigation drawer any help would be great please mention where is should make changes in my code