I create a simple searchview in android.
When i type a text in searchview the suggestion list shown as empty list
My code
res/xml/searchable.xml
<?xml version="1.0" encoding="UTF-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/search"
android:hint="#string/search_hint">
</searchable>
values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SearchViewDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="search">Search</string>
<string name="search_hint">Search the dictionary</string>
<string name="title_activity_searchable">SearchableActivity</string>
</resources>
menu/searchable.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/search"
android:title="#string/search"
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView" />
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings"/>
</menu>
layout/activity_searchable.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SearchableActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="120dp" >
</ListView>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.searchviewdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.searchviewdemo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.searchviewdemo.SearchableActivity"
android:label="#string/title_activity_searchable" >
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
<meta-data android:name="android.app.default_searchable"
android:value="com.example.searchviewdemo.SearchableActivity"/>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"></meta-data>
</activity>
</application>
</manifest>
SearchableActivity.java
package com.example.searchviewdemo;
import java.util.ArrayList;
import java.util.List;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.MatrixCursor;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;
import android.annotation.TargetApi;
public class SearchableActivity extends Activity {
private List<String> items=null;
private Menu menu;
ListView mylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchable);
//loaddata();
items=new ArrayList<String>();
Bundle extras=getIntent().getExtras();
if(extras!=null)
{
for(int i=0;i<7;i++)
{
items.add(extras.getString("values["+i+"]"));
}
}
mylist=(ListView)findViewById(R.id.listView1);
/*Intent intent=getIntent();
if(Intent.ACTION_SEARCH.equals(intent.getAction()))
{
String query=intent.getStringExtra(SearchManager.QUERY);
loadHistory(query);
}*/
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.searchable, menu);
this.menu=menu;
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
{
SearchManager manager=(SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView search=(SearchView)menu.findItem(R.id.search).getActionView();
search.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
//search.setIconifiedByDefault(false);
search.setOnQueryTextListener(new OnQueryTextListener(){
#Override
public boolean onQueryTextChange(String query) {
// TODO Auto-generated method stub
loadHistory(query);
//Toast.makeText(getApplicationContext(), "text changed", Toast.LENGTH_LONG).show();
return false;
}
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
});
}
return true;
}
//History
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void loadHistory(final String query1)
{
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
{
String[] columns=new String[]{"_id","text"};
Object[] temp=new Object[]{"0","default"};
final MatrixCursor cursor=new MatrixCursor(columns);
for(int i=0;i<items.size();i++)
{
temp[0]=i;
temp[1]=items.get(i);
cursor.addRow(temp);
}
SearchManager manager=(SearchManager)getSystemService(Context.SEARCH_SERVICE);
final SearchView search=(SearchView)menu.findItem(R.id.search).getActionView();
search.setSuggestionsAdapter(new ExampleAdapter(getBaseContext(),cursor,items));
mylist.setAdapter(new ExampleAdapter(getBaseContext(),cursor,items));
}
}
}
ExampleAdapter.java
package com.example.searchviewdemo;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class ExampleAdapter extends CursorAdapter {
private List<String> items;
private TextView text;
public ExampleAdapter(Context context,Cursor cursor,List<String> items)
{
super(context,cursor,false);
//this.items=new ArrayList<String>();
Log.e("msg","example adapter is called");
this.items=items;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
System.out.println("position"+cursor.getPosition()+":"+items.get(cursor.getPosition()));
text.setText(items.get(cursor.getPosition()));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
System.out.println("new view is called");
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.item, parent, false);
text=(TextView)view.findViewById(R.id.item);
return view;
}
![This is my output][1]
}
My list values are (two,three,four,five,six,seven,eight)
I am doing something wrong but don't know what i am doing wrong.
Please anyone help to solve this issue
My launcher activity
package com.example.searchviewdemo;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button button1;
List<String> items=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<String>();
//items.add("one");
items.add("two");
items.add("three");
items.add("four");
items.add("five");
items.add("six");
items.add("seven");
items.add("eight");
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(MainActivity.this,SearchableActivity.class);
for(int i=0;i<items.size();i++)
{
intent.putExtra("values["+i+"]", items.get(i));
}
startActivity(intent);
}
});
}
#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;
}
}
Edited searchacivity
SearchManager manager=(SearchManager)getSystemService(Context.SEARCH_SERVICE);
final SearchView search=(SearchView)menu.findItem(R.id.search).getActionView();
List<String> newlist=new ArrayList<String>();
for(int i=0;i<items.size();i++)
{
if(items.get(i).toString().trim().equals(query1))
{
newlist.add(items.get(i));
}
}
search.setSuggestionsAdapter(new ExampleAdapter(getBaseContext(),cursor,newlist));
try this way may this help you
#Edit 2
public void loadHistory(final String query1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
String[] columns = new String[] { "_id", "text" };
Object[] temp = new Object[] { "0", "default" };
MatrixCursor cursor1 = null;
final MatrixCursor cursor = new MatrixCursor(columns);
for (int i = 0; i < items.size(); i++) {
temp[0] = i;
temp[1] = items.get(i);
cursor.addRow(temp);
try {
if (items.get(i).startsWith(query1) && query1.length()>0 && !query1.equalsIgnoreCase("")) {
suggestionItems.add(items.get(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
// HashSet for not add Duplicate Value in List
HashSet<String> listToSet = new HashSet<String>(suggestionItems);
ArrayList<String> nameWithoutDuplicate = new ArrayList<String>(
listToSet);
List<String> suggestionName = nameWithoutDuplicate;
suggestionItems = suggestionName;
final SearchView search = (SearchView) menu.findItem(R.id.search)
.getActionView();
cursor1 = new MatrixCursor(columns);
if (suggestionItems.size() > 0) {
for (int i = 0; i < suggestionItems.size(); i++) {
if (suggestionItems.get(i) != null) {
temp[0] = i;
temp[1] = suggestionItems.get(i);
cursor1.addRow(temp);
}
}
search.setSuggestionsAdapter(new ExampleAdapter(
getBaseContext(), cursor1, suggestionItems));
}
mylist.setAdapter(new ExampleAdapter(getBaseContext(), cursor,
items));
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
System.out.println("position"+cursor.getPosition()+":"+items.get(cursor.getPosit ion()));
text.setText(items.get(cursor.getPosition()));
text.setTextColor(Color.RED);
}}
Related
I'm using a SearchView and I have added the search feature (that works) and now I'm trying to add a custom suggestion. The provider is created but when i type something query() is never called for some reasons.
Where am I wrong?
Here my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.chefme.chefme">
<uses-feature
android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<uses-feature
android:name="android.permission-group.MICROPHONE"
android:required="true"/>
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<!-- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<provider
android:name=".RecipeIngredientTabs.SuggestionProvider"
android:authorities="com.chefme.chefme.RecipeIngredientTabs.SuggestionProvider">
</provider>
<activity
android:name=".Startup"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RecipeIngredientTabs.Main"
android:label="#string/app_name"
android:launchMode="singleTop"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
<activity
android:name=".RecipeStep"
android:label="#string/title_activity_recipe_steps"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".RecipePreview.RecipePreview"
android:label="#string/title_activity_recipe_preview"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".ShoppingList.ShoppingList"
android:label="#string/title_activity_shopping_list"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Settings.Diets"
android:label="#string/title_activity_diets"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar"/>
<activity
android:name=".Favorite.FavoriteActivity"
android:label="#string/title_activity_favorite"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar"/>
<activity
android:name=".ownRecipesCamera.TakePicture"
android:label="#string/title_activity_take_picture"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar"/>
<activity
android:name=".Settings.Credits"
android:label="#string/title_activity_credits"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar"/>
</application>
</manifest>
Here my Provider:
package com.chefme.chefme.RecipeIngredientTabs;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.support.annotation.Nullable;
import DBUtility.Data;
public class SuggestionProvider extends ContentProvider{
#Override
public boolean onCreate() {
System.out.println("Creation Provider");
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
String query = uri.getLastPathSegment().toLowerCase(); //Dovrebbe essere chiamato tramite searchable.xml
System.out.println("write: "+ query);
String[] columns = new String[]{"_ID", "SUGGEST_COLUMN_TEXT_1", "SUGGEST_COLUMN_ICON_1", "SUGGEST_COLUMN_INTENT_DATA"};
MatrixCursor cursor = new MatrixCursor(columns);
Object[] row = new Object[]{0, Data.currentIngredients.get(0).getName(), Data.currentIngredients.get(0).getImage(), "Gigi"};
cursor.addRow(row);
return cursor;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues contentValues) {
return null;
}
#Override
public int delete(Uri uri, String s, String[] strings) {
return 0;
}
#Override
public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
return 0;
}
}
Here my searchable.xml:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/action_search" >
android:searchSuggestAuthority="com.chefme.chefme.RecipeIngredientTabs.SuggestionProvider
android:searchSuggestIntentAction="android.Intent.action.VIEW" >
</searchable>
Here my main:
package com.chefme.chefme.RecipeIngredientTabs;
import android.Manifest;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.chefme.chefme.NavbarActivity;
import com.chefme.chefme.R;
import java.io.File;
import DBUtility.Data;
public class Main extends NavbarActivity {
private SectionsPagerAdapter selectorPagerAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
private Toast backtoast;
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.replaceContentLayout(R.layout.main_content, super.CONTENT_LAYOUT_ID);
verifyDirectoryExists();
verifyStoragePermissions(this);
handleIntent(getIntent());
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, //host activity
drawer, //drawerLayout object
toolbar, //nav drawer icon to replace
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
selectorPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(selectorPagerAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
protected void onResume(){
super.onResume();
Data.active_main = true;
}
#Override
protected void onPause(){
super.onPause();
Data.active_main = false;
}
public void onBackPressed() {
if(backtoast!=null&&backtoast.getView().getWindowToken()!=null) {
finish();
} else {
backtoast = Toast.makeText(this, "Press back to exit", Toast.LENGTH_SHORT);
backtoast.show();
}
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
System.out.println("Searched: " + query);
}
else if (Intent.ACTION_VIEW.equals(intent.getAction())) { //Intent partito da SuggestionProvider
String query = intent.getDataString();
System.out.println("Suggested: " + query);
}
}
//------------------------------------------------------------------------------------------
// TAB SELECTOR FUNCTIONS
//------------------------------------------------------------------------------------------
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
if(position == 0)
return new TabFragmentIngredients();
if(position == 1)
return new TabFragmentRecipes();
else
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.name_ingredients_hint);
case 1:
return getString(R.string.name_recipes_hint);
}
return null;
}
}
//------------------------------------------------------------------------------------------
// MENU FUNCTIONS
//------------------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings: showOrderbyDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showOrderbyDialog() {
FragmentManager fm = getSupportFragmentManager();
OrderByDialog orderbyDialogDialog = new OrderByDialog();
orderbyDialogDialog.show(fm, "");
}
public static void verifyDirectoryExists(){
String folder_main = "GnammyRecipes";
File f = new File(Environment.getExternalStorageDirectory()+"/Pictures/", folder_main);
if (!f.exists()) {
f.mkdirs();
}
}
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}
Can you please try to change to this
android:searchSuggestAuthority="com.chefme.chefme.RecipeIngredientTabs.SuggestionProvider
to
android:searchSuggestAuthority="#string/application_package_name"
android:searchSuggestSelection=" ?"
Also you are missing meta-data tag
<meta-data
android:name="android.app.default_searchable"
android:value="com.chefme.chefme.RecipeIngredientTabs.YOURSEARCHACTIVITY" >
</meta-data>
Refer this link
https://developer.android.com/guide/topics/search/search-dialog.html
I'm new to Android. I read similar posts but I cannot solve my problem.
I added all my activities in androidManifest file, but I cannot move from Second Activity to ThirdActivity using Intent.
Here is MainActivity.java
package com.mobi.crazycalc;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent in= new Intent(MainActivity.this,SecondActivity.class);
MainActivity.this.startActivity(in);
MainActivity.this.finish();
}
}, 1000);
}
#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;
}
}
here is SecondActivity.java
package com.mobi.crazycalc;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SecondActivity extends Activity {
EditText name1;
EditText name2;
Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
name1= (EditText) findViewById(R.id.name1);
name2=(EditText) findViewById(R.id.name2);
goButton= (Button) findViewById(R.id.gobutton);
final String hisName=name1.getText().toString().trim();
final String herName=name2.getText().toString().trim();
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Love lv=new Love();
int result=lv.getLovePer(hisName, herName);
Intent in=new Intent(SecondActivity.this,ThirdActivity.class);
in.putExtra("Result", result);
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
Here is ThirdActivity.java
package com.mobi.crazycalc;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ThirdActivity extends Activity {
TextView meter;
Button goBackButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
meter = (TextView) findViewById(R.id.meter);
goBackButton = (Button) findViewById(R.id.gobackbutton);
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in=new Intent(ThirdActivity.this,SecondActivity.class);
startActivity(in);
}
});
Random ran= new Random();
for(int i=0;i<100;++i)
{
int ranNo=ran.nextInt(100);
meter.setText(ran.toString());
}
Bundle bund=getIntent().getExtras();
int res=bund.getInt("Result");
meter.setText(res);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.third, menu);
return true;
}
}
this is the manifest file-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobi.crazycalc"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.mobi.crazycalc.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.mobi.crazycalc.SecondActivity"
android:label="#string/title_activity_second" >
</activity>
<activity
android:name="com.mobi.crazycalc.ThirdActivity"
>
</activity>
</application>
</manifest>
activity-second.xml:
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e52850"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SecondActivity" >
<EditText
android:id="#+id/name1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp"
android:ems="10"
android:hint="#string/name1Edittext"
android:textColor="#color/almond" >
<requestFocus />
</EditText>
<Button
android:id="#+id/gobutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name2"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:background="#android:color/transparent"
android:text="#string/buttontext"
android:textColor="#color/aeroBlue" />
<EditText
android:id="#+id/name2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name1"
android:layout_below="#+id/name1"
android:layout_marginTop="41dp"
android:ems="10"
android:hint="#string/name2Edittext"
android:textColor="#color/almond" />
</RelativeLayout>
Try This one
And you can check this here
In MainActiviy
package com.mobi.crazycalc;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent in = new Intent(MainActivity.this, SecondActivity.class);
MainActivity.this.startActivity(in);
MainActivity.this.finish();
}
}, 1000);
}
#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;
}
}
In SecondAcivity
package com.mobi.crazycalc;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SecondActivity extends ActionBarActivity {
EditText name1;
EditText name2;
Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
name1 = (EditText) findViewById(R.id.name1);
name2 = (EditText) findViewById(R.id.name2);
goButton = (Button) findViewById(R.id.gobutton);
final String hisName = name1.getText().toString().trim();
final String herName = name2.getText().toString().trim();
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in = new Intent(SecondActivity.this, ThirdActivity.class);
in.putExtra("Result", "value");
startActivity(in);
}
});
}
#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_second, 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);
}
}
In Third activity
package com.mobi.crazycalc;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class ThirdActivity extends ActionBarActivity {
TextView meter;
Button goBackButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
meter = (TextView) findViewById(R.id.meter);
goBackButton = (Button) findViewById(R.id.gobackbutton);
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in = new Intent(ThirdActivity.this, SecondActivity.class);
startActivity(in);
}
});
Random ran = new Random();
for (int i = 0; i < 100; ++i) {
int ranNo = ran.nextInt(100);
meter.setText(ran.toString());
}
Bundle bund = getIntent().getExtras();
String res = bund.get("Result").toString();
meter.setText(res);
}
#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_third, 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);
}
}
and In menifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobi.crazycalc" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="#string/title_activity_second" >
</activity>
<activity
android:name=".ThirdActivity"
android:label="#string/title_activity_third" >
</activity>
</application>
</manifest>
Hope it will help you.
I want to make a search with suggestions.
after running the app and typing a string in my search box non of the following Logs Log.d("states","a onCreate"), Log.d("states",arg0.toString()), Log.d("states",query) or Log.d("states","searchactivity onCreate") execute.
What do I have to do do so the query() method in a.java or the onCreate() method in b.java are called?
Please dont send me to google developer documents its very confusing.
MainActivity.java
package com.example.searchapp;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.SearchView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("states","MainActivity onCreate");
ActionBar actionBar = getActionBar();
//actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
//searchView.setSubmitButtonEnabled(true);
searchView.setQueryRefinementEnabled(true);
return true;
}
}
a.java
package com.example.searchapp;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
public class a extends ContentProvider{
#Override
public int delete(Uri arg0, String arg1, String[] arg2) {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getType(Uri arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public Uri insert(Uri arg0, ContentValues arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean onCreate() {
// TODO Auto-generated method stub
Log.d("states","a onCreate");
return true;
}
#Override
public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
String arg4) {
// TODO Auto-generated method stub
Log.d("states",arg0.toString());
String query = arg0.getLastPathSegment().toLowerCase();
Log.d("states",query);
return null;
}
#Override
public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
// TODO Auto-generated method stub
return 0;
}
}
b.java
package com.example.searchapp;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class b extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("states","searchactivity onCreate");
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Log.d("states",query);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.searchapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="20" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<provider
android:name=".a"
android:authorities="com.example.searchapp.searchsuggestion">
</provider>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".b">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
</application>
</manifest>
searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="app_label"
android:hint="Search in tags"
android:searchSuggestAuthority="com.example.searchapp.searchsuggestion"
android:searchSuggestIntentAction="android.intent.action.VIEW" >
</searchable>
I think in your a-class you have to implement the getType()-method:
private UriMatcher uriMatcher;
#Override
public boolean onCreate() {
final String authority = "com.example.searchapp.searchsuggestion";
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
uriMatcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);
return true;
}
#Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case SEARCH_SUGGEST:
return SearchManager.SUGGEST_MIME_TYPE;
default:
throw new IllegalArgumentException("Unknown URL " + uri);
}
}
I'm trying to organize data recieved by SMS messages in specified ListView's.
I tried to create and activity which will contain 3 ListView's in one layout.
But, while running the activity it crashes.
Can someone help with this?
Here is the XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ListView
android:id="#+id/idList"
android:layout_width="112dp"
android:layout_height="384dp"
android:layout_gravity="center" >
</ListView>
<ListView
android:id="#+id/namesList"
android:layout_width="96dp"
android:layout_height="387dp"
android:layout_gravity="center" >
</ListView>
<ListView
android:id="#+id/phonesList"
android:layout_width="wrap_content"
android:layout_height="382dp"
android:layout_gravity="center" >
</ListView>
</LinearLayout>
And here is the activity code:
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DataLists extends ListActivity implements OnClickListener {
ListView idList, namesList, phonesList;
MyReciever mr;
ArrayList<String>ids= new ArrayList<String>();
ArrayList<String>names=new ArrayList<String>();
ArrayList<String>phones=new ArrayList<String>();
ArrayAdapter<String> idAdapter, namesAdapter, phonesAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.details_lists);
idList=(ListView)findViewById(R.id.idList);
namesList=(ListView)findViewById(R.id.namesList);
phonesList=(ListView)findViewById(R.id.phonesList);
idAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,ids );
idList.setAdapter(idAdapter);
namesAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
namesList.setAdapter(namesAdapter);
phonesAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, phones);
phonesList.setAdapter(phonesAdapter);
}
public void addItemToIdList(String st)
{
ids.add(st);
idAdapter.notifyDataSetChanged();
}
public void addItemToNamesList(String st)
{
names.add(st);
namesAdapter.notifyDataSetChanged();
}
public void addItemToPhonesList(String st)
{
phones.add(st);
phonesAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
private class MyReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle=intent.getExtras();
SmsMessage[]msgs=null;
if(bundle!=null)
{
Object[]pdus=(Object[]) bundle.get("pdus");
msgs=new SmsMessage[pdus.length];
for(int i=0;i<msgs.length;i++)
{
int index=0, prev=0;
String msgBody=msgs[i].getMessageBody().toString();
index=msgBody.indexOf(';');
prev=index;
String name=msgBody.substring(0, index);
addItemToNamesList(name);
msgBody=msgBody.substring(index+1);
index=msgBody.indexOf(';');
String id=msgBody.substring(prev, index);
addItemToIdList(id);
msgBody=msgBody.substring(index+1);
String phone=msgBody;
addItemToPhonesList(phone);
}
}
}
}
}
You have extended ListActivity. This is a convenience class that can be used to display a single ListView. The crash is clearly described in your logcat/stacktrace:
java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
Since your layout contains 3 ListViews, you probably can't use ListActivity anyway. Just change your activity to extend Activity and go from there.
I have created android apps, I have taken Listview and I want to display the data in listview using Baseadapter but my apps was giving me error in logcat. i searched lot cannot find relavant information.
logcat error:
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.oj2.exlistview/com.oj2.exlistview.TimeTrackerr}:
java.lang.ClassNotFoundException: com.oj2.exlistview.TimeTrackerr in loader
dalvik.system.PathClassLoader[/data/app/com.oj2.exlistview-1.apk]
In src folder I have three files
1)First is adapter class
2)Second is activity class and
3)This normal class having member fun and data member
1)Following is the adapter class
package com.oj2.exlistview;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class TimeTrackAdapter extends BaseAdapter {
ArrayList<TimeRecord> times = new ArrayList<TimeRecord>();
public TimeTrackAdapter() {
super();
times.add(new TimeRecord("23.43", "Feeling good"));
times.add(new TimeRecord("11.43", "hi this adapter"));
times.add(new TimeRecord("12.43", "I m Rocking it"));
times.add(new TimeRecord("13.43", "Feeling good"));
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return times.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return getItem(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.time_list_item, parent,false);
TimeRecord time = times.get(position);
TextView timeTextView = (TextView) convertView.findViewById(R.id.timeView);
timeTextView.setText(time.getTimes());
TextView noteTextView = (TextView) convertView.findViewById(R.id.noteView);
timeTextView.setText(time.getTimes());
}
return null;
}
}
2)second is the activity class
package com.oj2.exlistview;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class TimeTracker extends Activity{
TimeTrackAdapter timeTrackAdapter= null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
ListView listView = (ListView) findViewById(R.id.timeListView);
timeTrackAdapter = new TimeTrackAdapter();
listView.setAdapter(timeTrackAdapter);
listView.getAdapter();
}
}
3) following is the Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.oj2.exlistview"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.oj2.exlistview.TimeTrackerr"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Thanking you
your class name is
TimeTracker
and your wrote
android:name="com.oj2.exlistview.TimeTrackerr"
remove the last r from your manifest's activity attribute as below
android:name="com.oj2.exlistview.TimeTracker"
or just write
android:name=".TimeTracker"