View log messegase in the logCat - touch

I would like for a littel help.
i'm tring to extract "touch" infromation and send it. for debug i want to print to infomation i extract to the log. i used Log.v and it doesn't work. every time i touch the screen i see new messages but there are not what i wrote.i think i have a problem in my view definition.
i want to define all the screen.
attached are my code and log messages.
>1. "TouchScreen.java"
public class TouchScreenActivity extends Activity {
/** Called when the activity is first created. */
View mButtonLable;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButtonLable = findViewById(R.id.super_view);
mButtonLable.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int i, len, id;
float x, y, t;
len = motionEvent.getPointerCount();
float[][] touch = new float[len][4];
for (i = 0; i < len - 1; i++) {
id = motionEvent.getPointerId(i);
x = motionEvent.getX(i);
y = motionEvent.getY(i);
t = motionEvent.getEventTime();
touch[i][0] = x;*
touch[i][1] = y;
touch[i][2] = id;
touch[i][3] = t;
Log.v("TouchScreenActity", "x = " + x + ", y = " + y
+ ", id = " + id + ",t = " + t);
}
return false;
}
});
}
>2."main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<TextView
android:id="#+id/super_view"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="2"
android:background="#f00" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
my Logcat
>04-18 23:46:52.390: D/HierarchicalStateMachine(301): processMsg: SupplicantStartedState
>04-18 23:46:52.390: D/WifiStateMachine(301): SupplicantStartedState{ what=65574 when=-19ms }
>04-18 23:46:52.390: I/wpa_supplicant(19652): SCAN_RESULTS : [2]
>04-18 23:46:52.400: D/HierarchicalStateMachine(301): handleMessage: X
>04-18 23:46:52.400: D/HierarchicalStateMachine(301): handleMessage: E msg.what=65575
>04-18 23:46:52.400: D/HierarchicalStateMachine(301): processMsg: DisconnectedState
>04-18 23:46:52.400: D/WifiStateMachine(301): DisconnectedState{ what=65575 when=-17ms >obj=android.net.wifi.WifiStateMachine$StateChangeResult#40877448 }
>04-18 23:46:52.400: D/WifiStateMachine(301): setDetailed state, old =SCANNING and new >state=CONNECTING
>04-18 23:46:52.400: D/HierarchicalStateMachine(301): processMsg: ConnectModeState
>04-18 23:46:52.400: D/WifiStateMachine(301): ConnectModeState{ what=65575 when=-18ms >obj=android.net.wifi.WifiStateMachine$StateChangeResult#40877448 }
>04-18 23:46:52.400: D/HierarchicalStateMachine(301): handleMessage: X
>04-18 23:46:52.400: D/WpsStateMachine(301): InactiveState{ what=65575 when=-1ms >obj=android.net.wifi.WifiStateMachine$StateChangeResult#40877448 }
>04-18 23:46:52.460: I/wpa_supplicant(19652): Wireless event: new AP: 00:21:27:f5:3d:20
>04-18 23:46:52.460: I/wpa_supplicant(19652): CTRL-EVENT-STATE-CHANGE id=4 state=4 >BSSID=00:21:27:f5:3d:20
>04-18 23:46:52.460: V/WifiMonitor(301): Event [CTRL-EVENT-STATE-CHANGE id=4 state=4 >BSSID=00:21:27:f5:3d:20]
>04-18 23:46:52.460: D/HierarchicalStateMachine(301): handleMessage: E msg.what=65575
>04-18 23:46:52.460: D/HierarchicalStateMachine(301): processMsg: DisconnectedState
>04-18 23:46:52.470: I/wpa_supplicant(19652): Current ps mode is 0
>04-18 23:46:52.470: I/wpa_supplicant(19652): Associated with 00:21:27:f5:3d:20
>04-18 23:46:52.470: I/wpa_supplicant(19652): CTRL-EVENT-STATE-CHANGE id=4 state=7 >BSSID=00:00:00:00:00:00
>04-18 23:46:52.470: D/WifiStateMachine(301): DisconnectedState{ what=65575 when=-1ms >obj=android.net.wifi.WifiStateMachine$StateChangeResult#413643e0 }
>04-18 23:46:52.470: I/wpa_supplicant(19652): CTRL-EVENT-CONNECTED - Connection to >00:21:27:f5:3d:20 completed (reauth) [id=4 id_str=]
>04-18 23:46:52.470: D/WifiStateMachine(301): setDetailed state, old =CONNECTING and new >state=CONNECTING
>04-18 23:46:52.470: D/HierarchicalStateMachine(301): processMsg: ConnectModeState
>04-18 23:46:52.470: D/WifiStateMachine(301): ConnectModeState{ what=65575 when=-2ms >obj=android.net.wifi.WifiStateMachine$StateChangeResult#413643e0 }
>04-18 23:46:52.470: D/HierarchicalStateMachine(301): handleMessage: X
>04-18 23:46:52.470: D/WpsStateMachine(301): InactiveState{ what=65575 when=-1ms >obj=android.net.wifi.WifiStateMachine$StateChangeResult#413643e0 }

I think your problem is in the for loop declaration.
for (i = 0; i < len - 1; i++)
If your len would be 1, the body of this cycle will never be executed, aint it? Just change it to:
for (i = 0; i < len; i++)

Related

Store line renderer's all points as a object in XML file

I am facing a problem while storing Line Renderer's all point as a single object in XML file. What I am trying to do is draw something in the air using line renderer and store that drawing as a points in XML file to recreate it. I am able to save everything properly except every point is becoming a single object instead of generating under a single object. Below is my code:
AirDrawObject.cs
using UnityEngine;
[System.Serializable]
public class AirDrawObject
{
public string pointIndex;
public Vector3 pointPosition;
}
XMLDataExporter.cs
public AirDrawObject newAirDrawObject;
public ObjectDatabase objectDB;
public void SaveFeedback(GameObject parentGameObject)
{
Transform[] childObjects = parentGameObject.transform.GetComponentsInChildren<Transform>();
if (childObjects[i].gameObject.tag == "AirDraw")
{
LineRenderer lineRenderer = childObjects[i].gameObject.GetComponent<LineRenderer>();
int count = lineRenderer.positionCount;
int[] array = new int[count];
for (int l = 0; l < array.Length; l++)
{
newAirDrawObject = new AirDrawObject();
newAirDrawObject.pointIndex = "Point " + l.ToString();
newAirDrawObject.pointPosition = lineRenderer.GetPosition(l);
objectDB.airDrawObjectList.Add(newAirDrawObject);
}
}
}
XML File:
<airDrawObjectList>
<AirDrawObject>
<point>Point 0</point>
<pointPosition>
<x>-0.0537847765</x>
<y>0.03524115</y>
<z>0.518784344</z>
</pointPosition>
</AirDrawObject>
<AirDrawObject>
<point>Point 1</point>
<pointPosition>
<x>-0.0537847765</x>
<y>0.03524115</y>
<z>0.518784344</z>
</pointPosition>
</AirDrawObject>
<AirDrawObject>
<point>Point 2</point>
<pointPosition>
<x>-0.0537847765</x>
<y>0.03524115</y>
<z>0.518784344</z>
</pointPosition>
</AirDrawObject>
Expected Result:
<AirDrawObject>
<point>Point 1</point>
<pointPosition>
<x>-0.0537847765</x>
<y>0.03524115</y>
<z>0.518784344</z>
</pointPosition>
<point>Point 2</point>
<pointPosition>
<x>-0.0537847765</x>
<y>0.03524115</y>
<z>0.518784344</z>
</pointPosition>
<point>Point 3</point>
<point>Point 4</point>
</AirDrawObject>
<AirDrawObject>
....
</AirDrawObject>
Can someone tell me what I am doing wrong?
Why not simply make your class
[Serializable]
[XmlRoot("ObjectDatabase")]
public class ObjectDatabase
{
[XmlArray("AirDrawList")]
[XmlArrayItem("AirDraw")]
public List<XmlAirDraw> AirDrawList = new List<XmlAirDraw>();
}
[Serializable]
public class XmlAirDraw
{
[XmlArray("points")]
[XmlArrayItem("point")]
public List<Vector3> points = new List<Vector3>();
}
And then rather save like
public void SaveFeedback(GameObject parentGameObject)
{
objectDb.AirDrawList.Clear();
var lines = parentGameObject.transform.GetComponentsInChildren<LineRenderer>(true);
foreach (var line in lines)
{
if(!line.CompareTag("AirDraw")) continue;
line.GetPositions(out var linePoints);
var xmlInstance = new AirDrawInstance
{
points = linePoints;
};
objectDb.AirDrawList.Add(newAirDrawObject);
}
}
Note that I'm typing on smartphone but I hope the idea gets clear and this should generate XML like
<ObjectDataBase>
<AirDrawList>
<AirDraw>
<points>
<point>
<x>-0.0537847765</x>
<y>0.03524115</y>
<z>0.518784344</z>
</point>
<point>
<x>-0.0537847765</x>
<y>0.03524115</y>
<z>0.518784344</z>
</point>
...
</points>
</AirDraw>
<AirDraw>
<points>
...
</points>
</AirDraw>
...
</AirDrawList>
</ObjectDataBase>
So I figured it out by myself. I have changed my class for point and airDrawPoint like below.
AirDrawPoint.cs
[System.Serializable]
public class AirDrawPoint
{
public string index;
public float X;
public float Y;
public float Z;
}
AirDrawObject.cs
[System.Serializable]
public class AirDrawObject
{
public List<AirDrawPoint> pointList = new List<AirDrawPoint>();
}
XMLDataExporter.cs
if (childObjects[i].gameObject.tag == "AirDraw")
{
newAirDrawObject = new AirDrawObject();
LineRenderer lineRenderer = childObjects[i].gameObject.GetComponent<LineRenderer>();
int count = lineRenderer.positionCount;
int[] array = new int[count];
for (int l = 0; l < array.Length; l++)
{
point = new AirDrawPoint();
Vector3 position = lineRenderer.GetPosition(l);
point.index = "Point " + l.ToString();
point.X = position.x;
point.Y = position.y;
point.Z = position.z;
newAirDrawObject.pointList.Add(point);
}
objectDB.airDrawObjectList.Add(newAirDrawObject);
}

How to define copy constructor and deallocate pointer

I ran cppcheck, and it turns out that I need to have a copy constructor for this class. I do not know how to define a copy constructor in this case. Any suggestions?
class Simulator{
private:
int xMax;// = 40; //SIZE;
int yMax;// = 40; //xMax; // 40
//int TTMxSize = 4000;
//const int CarMxSize = 500;
//const int WaitListSize = 4000;
double base_price;// = 0.85 / 4;
double saev_vott;// = 0.35;
char* mode_output;// = "modeChoiceStats_supply_charge.csv";
vector<Car>** CarMx;//[xMax][yMax];
vector <Station>** ChStMx;//[xMax][yMax];
vector<int> **cellChargeCount;
vector<int> **cellChargeTime;
int timeTripCounts [288];
// Functions for program
public:
Simulator();
Simulator(int fleet_size, int seed, char* inputFile);
~Simulator();
bool loadParameters(char* input);
void printParameters();
void placeInitCars();
bool lookForCar (int x, int y, int r, int dist, int& cn);
void assignCar (int x, int y, int c, Trip* trp);
void setBusinessTripProbability();
void runSimulation();
};
Simulator::~Simulator()
{
for (int x=0; x<xMax; x++)
{
delete [] CarMx[x];
delete [] ChStMx[x];
delete [] cellChargeCount[x];
delete [] cellChargeTime[x];
}
for (int x=0; x<numZonesL; x++)
delete [] zoneSharesL[x];
for (int x=0; x<numZonesS; x++)
delete [] zoneSharesS[x];
delete [] CarMx;
delete [] ChStMx;
delete [] cellChargeCount;
delete [] cellChargeTime;
delete [] zoneSharesL;
delete [] zoneSharesS;
}
Also, I am getting Resource Leak error in the following function
bool Simulator::loadParameters(char* input)
{
FILE* inputfile;
inputfile = fopen(input, "r");
if (inputfile == NULL){
cout << "Could not open "<<input<<endl;
return false;
}
double inputVal = -1.0;
char* varStr;
char* valStr;
char instring [80];
while (!feof(inputfile))
{
fgets(instring, 80, inputfile);
comment = instring[0];
if (comment != '#' && comment != '\n')
{
varStr = strtok(instring, "=");
valStr = strtok(NULL, "\0");
if (strcmp (varStr, "xMax") == 0) {
inputVal = strtod(valStr, NULL);
xMax = 4 * (int) inputVal;
} else if (strcmp (varStr, "yMax") == 0) {
inputVal = strtod(valStr, NULL);
yMax = 4 * (int) inputVal;
}
}
return true; <<<<<<<<< RESOURCE LEAK: inputfile
}
Possible leak in this function: Pointer is not deallocated before being allocated.
void Simulator::setBusinessTripProbability()
{
businessTripProbability = new double[926];
businessTripProbability [ 0 ] = 0.0000 ;
businessTripProbability [ 1 ] = 0.0029 ;
businessTripProbability [ 2 ] = 0.0059 ;........... until [925]
I am a Cppcheck developer.
To create a copy constructor:
Simulator(const Simulator &sim);
If you do not plan to use the copy constructor, it's better to delete it:
Simulator(const Simulator &) = delete;
Resource leak: You need to use fclose(inputfile)
Possible leak: Imagine this code:
Simulator simulator;
simulator.setBusinessTripPossibility();
simulator.setBusinessTripPossibility();
There is a memory leak here. The businessTripProbability is allocated twice and there is no deallocation. You might have a rule that the public method setBusinessTripPossibility() will never be called twice. But in my humble opinion you should not design classes with such rule. Try to allow arbitrary use of the public class interface.

OrientDB: why always : Class already exists in current database

I'm testing the OrientDB and unfamiliar with the OrientDB-Graph API. And now I copied the code on the net, it rises the Exception.
Next is my code:
import com.tinkerpop.blueprints.impls.orient.*;
import com.tinkerpop.blueprints.Element.*;
import java.util.*;
class OrientInsert {
public static void testInsertion(OrientGraphNoTx graph) {
System.out.println(new Date());
int count = 1000;
for (int i = 0; i < count; ++i) {
OrientVertex vertex1 = graph.addVertex("class:CLASS1", "prop1", Integer.toString(i), "prop2", "22", "prop3", "3333");
for (int j = 0; j < count; ++j) {
OrientVertex vertex2 = graph.addVertex("class:CLASS2", "prop1", Integer.toString(i + j / 1000), "prop2", "22", "prop3", "3333");
graph.addEdge(null, vertex1, vertex2, "v1v2");
}
}
graph.commit();
System.out.println(new Date());
}
public static void main(String[] args) {
OrientGraphFactory factory = new OrientGraphFactory("remote:10.240.137.12/test", "admin", "admin");
OrientGraphNoTx graph = factory.getNoTx();
OrientInsert.testInsertion(graph);
}
} `
And the output is:
Mar 29, 2016 11:45:19 AM com.orientechnologies.common.log.OLogManager log
INFO: OrientDB auto-config DISKCACHE=3,725MB (heap=14,288MB os=64,292MB disk=7,451MB)
Tue Mar 29 11:45:19 CST 2016
Exception in thread "main" com.orientechnologies.orient.server.distributed.ODistributedException: Error on execution distributed COMMAND
at com.orientechnologies.orient.server.distributed.ODistributedStorage.command(ODistributedStorage.java:346)
at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:67)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.command(ONetworkProtocolBinary.java:1323)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.executeRequest(ONetworkProtocolBinary.java:400)
at com.orientechnologies.orient.server.network.protocol.binary.OBinaryNetworkProtocolAbstract.execute(OBinaryNetworkProtocolAbstract.java:223)
at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:77)
Caused by: com.orientechnologies.orient.core.exception.OSchemaException: Class CLASS1 already exists in current database
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.doCreateClass(OSchemaShared.java:983)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass(OSchemaShared.java:415)
at com.orientechnologies.orient.core.metadata.schema.OSchemaProxy.createClass(OSchemaProxy.java:127)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLCreateClass.execute(OCommandExecutorSQLCreateClass.java:179)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.execute(OCommandExecutorSQLDelegate.java:90)
at com.orientechnologies.orient.server.distributed.task.OSQLCommandTask.execute(OSQLCommandTask.java:116)
at com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin.executeOnLocalNode(OHazelcastPlugin.java:810)
at com.orientechnologies.orient.server.hazelcast.ODistributedWorker.onMessage(ODistributedWorker.java:279)
at com.orientechnologies.orient.server.hazelcast.ODistributedWorker.run(ODistributedWorker.java:103)
Apparently, it first inserts the vertex1 and vertex2 into the graphDatabase, and creates class1 and class2. But when it comes to the second insertion, it still wants to create the class1 and class2. Why? how can i control the creation of class. But, so many users use this api for testing.
Try this code:
public static void main(String[] args) {
OrientGraphFactory factory = new OrientGraphFactory("remote:localhost/test", "admin", "admin");
OrientGraphNoTx graph = factory.getNoTx();
OrientInsert.testInsertion(graph);
graph.shutdown();
System.out.println("");
System.out.println("End main");
}
public static class OrientInsert {
public static void testInsertion(OrientGraphNoTx graph) {
System.out.println(new Date());
int count = 1000;
//create class 1
OClass clVertice1;
OrientVertex vVertice1;
clVertice1 = graph.createVertexType("CLASS1", "V");
clVertice1.createProperty("prop1", OType.STRING);
clVertice1.createProperty("prop2", OType.STRING);
clVertice1.createProperty("prop3", OType.STRING);
//create class 2
OClass clVertice2;
OrientVertex vVertice2;
clVertice2 = graph.createVertexType("CLASS2", "V");
clVertice2.createProperty("prop1", OType.STRING);
clVertice2.createProperty("prop2", OType.STRING);
clVertice2.createProperty("prop3", OType.STRING);
for (int i = 0; i < count; ++i) {
System.out.println("");
System.out.println("i :"+i+" -------------------" );
//....class 1
vVertice1 = graph.addVertex("class:CLASS1");
vVertice1.setProperties("prop1", Integer.toString(i));
vVertice1.setProperties("prop2", "22");
vVertice1.setProperties("prop3", "3333");
for (int j = 0; j < count; ++j) {
System.out.print("");
System.out.print(j+" ");
//...class 2
vVertice2 = graph.addVertex("class:CLASS2");
vVertice2.setProperties("prop1", Integer.toString(i + j / 1000));
vVertice2.setProperties("prop2", "22");
vVertice2.setProperties("prop3", "3333");
//edge
graph.addEdge(null, vVertice1, vVertice2, "v1v2");
}
}
}
}
The result is this (i selected only 2 vertex with limit 100 E)

Creating a Linked list with Structs - C++

I was writing a program which could read an input file and store the read data in nodes linked by a "link list". However, I was getting a few errors:
In constructor List::List(), no match for 'operator =' in *((List*)this)->List::list[0] = 0
In constructor Polynomial::Polynomial(): no match for 'operator =' in *((Polynomial*)this)->Polynomial::poly = (operator new(400u), (<statement>), ...)
I have a feeling where I do: I try to access a certain node through an array is where I go wrong, however, I can't figure it out much.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
enum result{success, failure};
struct Node
{
double coefficient;
int power;
Node();
Node(double coef, int pwr);
};
struct List
{
Node *list[100];
//Default constructor
List();
};
Node::Node()
{
coefficient = 0;
power = 0;
}
List::List()
{
*list[0] = NULL;
}
Node::Node(double coef, int pwr)
{
coefficient = coef;
power = pwr;
}
class Polynomial
{
public:
Polynomial();
result multiply(Polynomial &p, Polynomial &q);
result add(Polynomial p, Polynomial &q);
void initialize(ifstream &file);
void simplify(Polynomial &var);
void print_poly();
~Polynomial();
private:
List *poly; //Store the pointer links in an array
Node first_node;
int val;
};
Polynomial::Polynomial()
{
*poly = new List();
}
Polynomial::void initialize(ifstream &file)
{
int y[20];
double x[20];
int i = 0, j = 0;
//Read from the file
file >> x[j];
file >> y[j];
first_node(x[j], y[j++]); //Create the first node with coef, and pwr
*poly->list[i] = &first_node; //Link to the fist node
//Creat a linked list
while(y[j] != 0)
{
file >> x[j];
file >> y[j];
*poly->list[++i] = new Node(x[j], y[j++]);
}
val = i+1; //Keeps track of the number of nodes
}
Polynomail::result multiply(Polynomial &p, Polynomial &q)
{
int i, j, k = 0;
for(i = 0; i < p.val; i++)
{
for(j = 0; j < q.val; j++)
{
*poly->list[k] = new Node(0, 0);
*poly->list[k].coefficient = (p.poly->list[i].coefficient)*(q.poly->list[j].coefficient);
*poly->list[k++].power = (p.poly->list[i].power)+(q.poly->list[j].power);
}
}
val = k+1; //Store the nunber of nodes
return success;
}
Polynomial::void simplify(Polynomial &var)
{
int i, j, k = 0;
//Create a copy of the polynomial
for(j = 0; j < var.val; j++)
{
*poly->list[j] = new Node(0, 0);
*poly->list[j].coefficient = var.poly->list[j].coefficient;
*poly->list[j].power = var.poly->list[j].power;
}
//Iterate through the nodes to find entries which have the same power and add them, otherwise do nothing
for(k = 0; k < var.val; k++)
{
for(i = k; i < var.val;)
{
if(*poly->list[k].power == var.poly->list[++i].power)
{
if(*poly->list.power[0] == 0)
{
NULL;
}
else
{
*poly->list[k].coefficient = *poly->list[k].coefficient + var.poly->list[i].ceofficient;
var.poly->list[i] = Node(0, 0);
}
}
}
}
}
Polynomial::void print_pol()
{
int i = 0;
for(i = 0; i < temp.val; i++)
{
cout << "Coefficient: " << temp.poly->list[i].coefficient << ", and " << "Power: " << temp.poly->list[i].power << endl;
}
}
The problem is a wrong dereference. Line 34 should probably be
list[0] = NULL; // remove the *
You try to assign the value NULL to a variable of the type Node, but you probably mean a pointer to Node.
The very same is true in line 63.
In addition, line 66 sould probably b:
void Polynomial::initialize(ifstream &file) // start with return type

about MultiAutoCompleteTextView

public class testMultiAutoCompleteTextView extends ListActivity {
/** Called when the activity is first created. */
private MultiAutoCompleteTextView searchEdit;
Button okButton;
private ArrayAdapter<String> adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mStrings);
setListAdapter(adapter);
searchEdit = (MultiAutoCompleteTextView) findViewById(R.id.search_box);
searchEdit.addTextChangedListener(filterTextWatcher);
searchEdit.setTokenizer(new SpaceTokenizer());
searchEdit.setAdapter(adapter);
searchEdit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String t = ((TextView) v).getText().toString();
String f = searchEdit.getText().toString();
int s = searchEdit.getSelectionStart();
int i = s;
while (i > 0 && f.charAt(i - 1) != ' ') {
i--;
}
adapter.getFilter().filter(t.substring(i, s));
}
});
okButton = (Button) findViewById(R.id.ok);
okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bundle stats = new Bundle();
stats.putString("ConversationName", searchEdit.getText()
.toString());
Intent i = new Intent();
i.putExtras(stats);
setResult(RESULT_OK, i);
finish();
}
});
searchEdit.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
|| keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
|| keyCode == KeyEvent.KEYCODE_DPAD_UP
|| keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
String t = ((TextView) v).getText().toString();
String f = searchEdit.getText().toString();
int s = searchEdit.getSelectionStart();
int i = s;
while (i > 0 && f.charAt(i - 1) != ' ') {
i--;
}
adapter.getFilter().filter(t.substring(i, s));
return false;
}
return false;
}
});
getListView().setOnItemClickListener(
new ListView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String t = adapter.getItem(position);
String f = searchEdit.getText().toString();
int s = searchEdit.getSelectionStart();
int i = s;
while (i > 0 && f.charAt(i - 1) != ' ') {
i--;
}
searchEdit.getText().insert(s, t.substring(s - i));
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
searchEdit.removeTextChangedListener(filterTextWatcher);
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
okButton.setEnabled(searchEdit.getText().toString().trim()
.length() > 0);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
public class SpaceTokenizer implements Tokenizer {
public int findTokenStart(CharSequence text, int cursor) {
int i = cursor;
while (i > 0 && text.charAt(i - 1) != ' ') {
i--;
}
while (i < cursor && text.charAt(i) == ' ') {
i++;
}
return i;
}
public int findTokenEnd(CharSequence text, int cursor) {
int i = cursor;
int len = text.length();
while (i < len) {
if (text.charAt(i) == ' ') {
return i;
} else {
i++;
}
}
return len;
}
public CharSequence terminateToken(CharSequence text) {
int i = text.length();
while (i > 0 && text.charAt(i - 1) == ' ') {
i--;
}
if (i > 0 && text.charAt(i - 1) == ' ') {
return text;
} else {
if (text instanceof Spanned) {
SpannableString sp = new SpannableString(text + " ");
TextUtils.copySpansFrom((Spanned) text, 0, text.length(),
Object.class, sp, 0);
return sp;
} else {
return text + " ";
}
}
}
}
private String[] mStrings = {
"Vacherin-Fribourgeois", "Valencay", "Vasterbottenost", "Venaco", "Vendomois",
"Vieux Corse", "Vignotte", "Vulscombe", "Waimata Farmhouse Blue",
"Washed Rind Cheese (Australian)", "Waterloo", "Weichkaese", "Wellington",
"Wensleydale", "White Stilton", "Whitestone Farmhouse", "Wigmore", "Woodside Cabecou",
"Xanadu", "Xynotyro", "Yarg Cornish", "Yarra Valley Pyramid", "Yorkshire Blue",
"Zamorano", "Zanetti Grana Padano", "Zanetti Parmigiano Reggiano"};
}
my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical"
android:drawingCacheQuality="high">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal">
<MultiAutoCompleteTextView
android:layout_marginLeft="1dip"
android:layout_marginTop="1dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="fill_parent"
android:dropDownHeight="0px"
android:hint="#string/To"
android:id="#+id/search_box"
></MultiAutoCompleteTextView>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
android:id="#+id/ok"
android:enabled="false"
/>
</LinearLayout>
<ListView android:id="#android:id/list" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_weight="1" />
</LinearLayout>
it give me ERROR/AndroidRuntime(423): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.testMultiAutoCompleteTextView/com.test.testMultiAutoCompleteTextView.testMultiAutoCompleteTextView}: java.lang.NullPointerException
at onCreate method before to call
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mStrings);
you have to set you layout
setContentView(R.layout.you_xml_file_name);