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"
Related
I am making an app, where a server in java sends a Place Array and other stuff in other activities. so I create a service to connect to the server from different activities. I have not implement server connection yet but I am simulating the server response, which I pass as parameter to an adapter (the adapter is tested), that I create to show this places in a ListView. so I got my Place array in my activity and I set it to the return object from a method in the service, but when I run the app it crashes and I got this error message:
java.lang.NullPointerException: Attempt to invoke virtual method
'com.remedialguns.smartourist.Place[]
com.remedialguns.smartourist.ConnectionService.getPlaces()' on a null
object.
UPDATE now is te same error but in myAdapter class when name.setText...
so this is my service.
package com.remedialguns.smartourist;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Locale;
public class ConnectionService extends Service {
Socket s;
PrintStream os;
private static final String TAG="com.remedialguns.smartourist";
private final IBinder myBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return myBinder;
}
public void sendProfileData(){
//send profile data to server
}
public Place[] getPlaces(){
Place[] PlacesToShow = new Place[10];
//F̶a̶k̶e̶ ̶d̶a̶t̶a̶ Test data
PlacesToShow[0]= new Place("MUSEO","Museo Nacional Agropecuario", 0.15, 0.4, 0.12);
PlacesToShow[1]= new Place("MUSEO","Museo Arqueológico Junín",0.10, 0.78, 0.44);
PlacesToShow[2]= new Place("MUSEO","Museo Botero", 0.2, 0.8, 0.08);
PlacesToShow[3]= new Place("MUSEO","Museo de Zea", 0.3, 0.65, 0.23);
PlacesToShow[4]= new Place("MUSEO","MUSEO DEL ORO", 0.13, 0.56, 0.12);
PlacesToShow[5]= new Place("MUSEO","MUSEO DE ARTE COLONIAL", 0.3, 0.67, 0.14);
PlacesToShow[6]= new Place("MUSEO","MUSEO HISTORICO DE LA POLICIA NACIONAL", 0.34, 0.3, 0.33);
PlacesToShow[8]= new Place("MUSEO","MUSEO DE LOS NIÑOS", 0.05, 0.65, 0.03);
PlacesToShow[7]= new Place("MUSEO","Museo Nacional", 0.15, 0.4, 0.12);
PlacesToShow[9]= new Place("MUSEO","MUSEO MILITAR", 0.07, 0.5, 0.6);
return PlacesToShow;
}
public class LocalBinder extends Binder {
ConnectionService getService(){
return ConnectionService.this;
}
}
}
this is my activity with my ListView and adapter.(UPDATE)
package com.remedialguns.smartourist;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.IBinder;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import com.remedialguns.smartourist.ConnectionService.LocalBinder;
import com.google.android.gms.location.places.Places;
public class ListActivity extends AppCompatActivity {
ConnectionService tcpService;
boolean isBound=false;
//Place[] PlacesToShow=tcpService.getPlaces();
Place[] PlacesToShow=new Place[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = new Intent(this, ConnectionService.class);
bindService(i, myConnection, Context.BIND_AUTO_CREATE);
// PlacesToShow=tcpService.getPlaces();
if (isBound) {
PlacesToShow = tcpService.getPlaces();
}
//Place[] PlacesToShow=tcpService.getPlaces();
ListAdapter MyAdapter = new MyAdapter(this, PlacesToShow);
ListView ListPlaces=(ListView) findViewById(R.id.MyList);
ListPlaces.setAdapter(MyAdapter);
ListPlaces.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Context context = view.getContext();
TextView textViewItem = ((TextView)view.findViewById(R.id.name));
String name =textViewItem.getText().toString();
TextView textViewItem2 = (TextView)findViewById(R.id.description);
String descripcion=textViewItem2.getText().toString();
Toast.makeText(context,"lugar: "+name+", descripcion: "+descripcion,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private ServiceConnection myConnection=new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
tcpService = binder.getService();
PlacesToShow = tcpService.getPlaces();
isBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
isBound=false;
}
};
}
this is my activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_list"
tools:context="com.remedialguns.smartourist.ListActivity">
<!-- <TextView
android:id="#+id/answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="these are the places that our smart monkeys had find for you."/>
-->
<ListView
android:id="#+id/MyList"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
this is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.remedialguns.smartourist" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".RealMainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
</activity>
<activity
android:name=".ListActivity"
android:label="#string/app_name"
android:parentActivityName=".RealMainActivity"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.remedialguns.smartourist.RealMainActivity" />
</activity>
<service
android:name=".ConnectionService"
android:enabled="true"
android:exported="true" >
</service>
</application>
</manifest>
this is my adapter class
package com.remedialguns.smartourist;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<Place> {
MyAdapter(Context context, Place[] places){
super(context, R.layout.visual_place, places);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater MyInflater = LayoutInflater.from(getContext());
View placeView = MyInflater.inflate(R.layout.visual_place, parent, false);
Place singlePlaceItem=getItem(position);
TextView name=(TextView) placeView.findViewById(R.id.name);
ImageView icon =(ImageView) placeView.findViewById(R.id.icon);
TextView description = (TextView) placeView.findViewById(R.id.description);
name.setText(singlePlaceItem.getName().toString());
icon.setImageResource(R.mipmap.ic_launcher);
description.setText("Cost "+singlePlaceItem.getCost()+", distance "+singlePlaceItem.getDistance()+", rate "+singlePlaceItem.getRate()+" *");
return placeView;
}
}
please help me.
Here:
bindService(i, myConnection, Context.BIND_AUTO_CREATE);
Place[] PlacesToShow=new Place[10];
PlacesToShow=tcpService.getPlaces();
tcpService is null probably using is to call getPlaces() method before onServiceConnected method is called.
Use isBound to check onServiceConnected is called or not before using tcpService object:
if(isBound){
//
PlacesToShow=tcpService.getPlaces();
}
and also use onServiceConnected method as:
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
tcpService = binder.getService();
PlacesToShow=tcpService.getPlaces();
isBound=true;
}
Also make sure added ConnectionService in AndroidManifest.xml as service.
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);
}}
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);
}
}
Hi I want to play a media(video) file on surfaceview, so I am trying in follwing way.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myProject" >
<permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/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>
</application>
</manifest>
activity_main.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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<SurfaceView
android:id="#+id/surfView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Then I have created a /raw folder under /res folder and added a video(newmovie.mp4) in it.
Now In MainActivity I am trying to play that video in this way.
package com.example.myProject;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.app.Fragment;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.media.MediaPlayer.OnPreparedListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity implements SurfaceHolder.Callback,OnPreparedListener{
private MediaPlayer mediaPlayer;
private SurfaceHolder vidHolder;
private SurfaceView vidSurface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vidSurface = (SurfaceView) findViewById(R.id.surfView);
vidHolder = vidSurface.getHolder();
vidHolder.addCallback(this);
vidHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container,
false);
return rootView;
}
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.start();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
String fileName = "android.resource://" + getPackageName() + "/" + R.raw.newmovie;
mediaPlayer.setDataSource(this, Uri.parse(fileName));
mediaPlayer.setDisplay(vidHolder);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepare();
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
But I am getting error as 'E/MediaPlayer﹕ Error (1,-38)' after running this application as a result getting blank screen.
Also getting error as 'E/MediaPlayer﹕ Should have subtitle controller already set' which can be neglected as it will not stop to play video file.
When I tried to debug and see the file-name at run-time is like "android.resource://com.example.myProject/21348349", but my video resides in res/raw/ folder. How android gets my video at run-time ?
Can anyone guide me for this what is the meaning of this error and how can I resolve it.
I have an expandablelistview as shown below. I've made it so that a toast message will pop up when each child is clicked. I need each of the children to start their own activity/fragment, which required individual onClick() methods. Does anybody know how this can be achieved? Thanks. NOTE: I am using SimonVT's slidingmenu library and I'm pretty new to android programming.
MainActivity.java:
package press.linx.expandablelistdemo;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.xml.sax.SAXException;
import net.simonvt.menudrawer.MenuDrawer;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
ExpandableListView exv;
MenuDrawer mDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDrawer = MenuDrawer.attach(this);
mDrawer.setContentView(R.layout.activity_main);
mDrawer.setMenuView(R.layout.leftmenu);
exv=(ExpandableListView)findViewById(R.id.expandableListView1);
exv.setAdapter(new MyAdapter(this));
exv.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
String itemclicked = MyAdapter.childList[groupPosition][childPosition];
Toast.makeText(getApplicationContext(), "you clicked " + itemclicked, Toast.LENGTH_SHORT).show();
return false;
}
});
}
private void setListAdapter(SimpleAdapter adapter) {
// TODO Auto-generated method stub
}
#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;
}
}
MyAdapter.java
package press.linx.expandablelistdemo;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseExpandableListAdapter {
private Context context;
Typeface typeface;
String []parentList = {"Tech", "Best Of", "Art & Design", "Other"};
static String [][] childList = {
{
"All Tech", "Reviews", "Gaming", "Gadgets"
},
{
"Android"
},
{
"Architecture"
},
{
"Infographics"
}
};
public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context=context;
}
#Override
public Object getChild(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getChildId(int arg0, int arg1) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
//typeface = Typeface.createFromAsset(context.getAssets(), "font/robotochild.ttf");
TextView tv = new TextView(context);
tv.setText(childList[groupPosition][childPosition]);
tv.setPadding(30, 10, 0, 10);
tv.setTextSize(15);
//tv.setTypeface(typeface);
tv.setTextColor(Color.WHITE);
return tv;
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return childList[groupPosition].length;
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return parentList.length;
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TextView tv = new TextView(context);
typeface = Typeface.createFromAsset(context.getAssets(), "font/roboto.ttf");
tv.setText(parentList[groupPosition]);
tv.setPadding(50, 10, 0, 10);
tv.setTextSize(20);
tv.setTextColor(Color.WHITE);
tv.setTypeface(typeface);
return tv;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
menulistview.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=".MainActivity"
android:background="#drawable/geowall">
<ExpandableListView
android:id="#+id/expandableListView1"
android:groupIndicator="#null"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:padding="3dp" >
</ExpandableListView>
!
If you want differing functionalities per button, consider storing them as the buttons' tag property (in the XML layout). The View v parameter in your onChildClick listener is the View of the child being clicked; it can then be used to retrieve the tag, like so:
v.getTag();
You could either have a switch-case block to call the correct activity based on the tag, or store the exact name of the activity in the tag and pass that in via reflection to retrieve the class for the activity. Alternatively, you could store a HashMap mapping the tag-names to Activity classes/variables.
This might be you are looking for.
Let’s get start by creating a project in Eclipse IDE.
Create a new project by going to File ⇒ New Android Project. Fill all the details and name your activity as AndroidListViewActivity.
Once the project is created open your main activity java file (in this case AndroidListViewActivity.java) and extend the class from ListActivity.
public class AndroidListViewActivity extends ListActivity {
3. Now we need a string resources file to store all list item labels. So create an XML file under values folder and name it as list_data.xml and paste the following code.
( Right Click on res/values ⇒ New ⇒ Android XML File)
list_data.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="adobe_products">
<item>Adobe After Effects</item>
<item>Adobe Bridge</item>
<item>Adobe Dreamweaver</item>
<item>Adobe Edge</item>
<item>Adobe Fireworks</item>
<item>Adobe Flash</item>
<item>Adobe Photoshop</item>
<item>Adobe Premiere</item>
<item>Adobe Reader</item>
<item>Adobe Illustrator</item>
</string-array>
</resources>
In ListView each list item will be an xml layout, so we can customize each list item. Create an XML file under res/layout folder and name it as list_item.xml and type the following code. This xml layout will be single list item row.
( Right Click on res/layout ⇒ New ⇒ Android XML File)
Now open your main activity java file (AndroidListViewActivity.java) and type the following code. In the following code i am importing all xml resources data and storing them in an Array. On the next step i am binding array to ListAdapter.
AndroidListViewActivity.java
package com.androidhive.androidlistview;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
}
}
Now run your project you can see listview with list of array items. But on clicking single list item you can see no action. So we need to start new activity on selecting single list item.
Launching new Activity on selecting single list item
In my previous article i had explained how to switch between screens. Here i am going to show single list item details in new screen.
Now create new activity class under src folder. Right Click on src/package folder ⇒ New ⇒ Class and name it as SingleListItem. (SingleListItem.java)
Open your AndroidListViewActivity.java and modify the code to following. In the following code i am getting the selected list item string(product name) and sending it to new Activity.
AndroidListViewActivity.java
package com.androidhive.androidlistview;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, adobe_products));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("product", product);
startActivity(i);
}
});
}
}
Now in new activity we need to display the received from listview activity.
Create a new xml file under res/layout and name it as single_list_item_view.xml and type the following code. This XML file will be layout for SingleListItem.java
single_list_item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/product_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:padding="10dip"
android:textColor="#ffffff"/>
</LinearLayout>
Now open your second activity file i.e SingleListItem.java and paste the following code.
SingleListItem.java
package com.androidhive.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
}
}
The final step is to add an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.androidlistview"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AndroidListViewActivity"
android:label="Android List View">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SingleListItem"
android:label="Single Item Selected"></activity>
</application>
</manifest>
Finally run your project by right clicking on your project folder ⇒ Run As ⇒ 1 Android Application.