I am very new in android and trying to develop application to load all mp3 files from server to list-view and by clicking list item it should play that mp3 file directly from server.
Somehow i am able to list all mp3 files from server to list-view but when i click on list-view's item to play that particular song it giving me following error.
Logcat
02-18 11:49:58.266: E/AndroidRuntime(8276): FATAL EXCEPTION: main
02-18 11:49:58.266: E/AndroidRuntime(8276): java.lang.ClassCastException: java.net.URL cannot be cast to java.lang.String
02-18 11:49:58.266: E/AndroidRuntime(8276): at iqual.fidol_final.ServerFileList$1.onItemClick(ServerFileList.java:72)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.widget.AdapterView.performItemClick(AdapterView.java:295)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.widget.AbsListView.performItemClick(AbsListView.java:1073)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2577)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.widget.AbsListView$1.run(AbsListView.java:3302)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.os.Handler.handleCallback(Handler.java:605)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.os.Handler.dispatchMessage(Handler.java:92)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.os.Looper.loop(Looper.java:154)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.app.ActivityThread.main(ActivityThread.java:4624)
02-18 11:49:58.266: E/AndroidRuntime(8276): at java.lang.reflect.Method.invokeNative(Native Method)
02-18 11:49:58.266: E/AndroidRuntime(8276): at java.lang.reflect.Method.invoke(Method.java:511)
02-18 11:49:58.266: E/AndroidRuntime(8276): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
02-18 11:49:58.266: E/AndroidRuntime(8276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
02-18 11:49:58.266: E/AndroidRuntime(8276): at dalvik.system.NativeStart.main(Native Method)
Java Code
public class ServerFileList extends Activity implements
OnBufferingUpdateListener, OnErrorListener, OnPreparedListener {
Uri uri;
URL urlAudio;
ListView mListView;
PlaySongAsy play;
ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
MediaPlayer mp = new MediaPlayer();
private List<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.serverfilelist);
mListView = (ListView) findViewById(R.id.listAudio);
if (Const.server == 0) {
new getAudiofromServer().execute();
} else {
new getVideofromServer().execute();
}
// new downloadAudio().execute();
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// playSong(urlAudio + myList.get(position));
play = (PlaySongAsy) new PlaySongAsy(myList.get(position)
.replace(" ", "%20").trim()).execute();
}
});
}
class PlaySongAsy extends AsyncTask<String, Void, Boolean> {
String baseURL;
public PlaySongAsy(String baseURL) {
this.baseURL = baseURL;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = ProgressDialog.show(ServerFileList.this,
" Buffering...", "please wait..", false);
pDialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
new Thread() {
#Override
public void run() {
play(baseURL);
}
}.start();
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// progressDialog.dismiss();
}
}
private void play(String baseURL) {
Uri myUri = Uri.parse(baseURL);
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
// mp.setVolume(5.F, 5.F);
Log.d("", "LoadClip Done");
} catch (Throwable t) {
Log.d("", t.toString());
}
}
public void updateProgress(int currentSize, int totalSize) {
TextView mTextView = new TextView(ServerFileList.this);
mTextView.setText(Long.toString((currentSize / totalSize) * 100) + "%");
}
}
The code:
myList.get(position)
is implicitly casting the element of myList to a String, since myList is a List<String>. This is failing because you managed to insert a URL object into myList.
Enable "unchecked cast" warnings, and you should see a warning where you are inserting into myList.
Two possible fixes:
Eliminate the unchecked cast. Part of that will probably involve calling .toString() on your URL before adding it to myList.
Or, change the type of myList to List<URL>, and then do the .toString() call inside onItemClick.
Which one you go with depends on the type you'd like myList to have.
I think that myList contains wrong objects. You put URIs inside it, not Strings. Use toString method on Uris when you filling list.
Find where you do this:
myList.add((String)uri);
and change to:
myList.add(uri.toString());
Invoke toString() method on the URL object to get the string form.
Refer http://docs.oracle.com/javase/6/docs/api/java/net/URL.html#toString%28%29
Your `Exception saying...
java.lang.ClassCastException: java.net.URL cannot be cast to java.lang.String
Which boldly indicating, you are trying to cast an URL to a String object...that means, baseURL is an URL object but you are trying to cast it to a String object, that's why Exception happening.
Now, Change the following...
String baseURL;
to
Uri baseURL;
As well as, where you are referencing baseURL as a String, change them as Uri.
Try removing all the unnecessary spaces in your URL by calling trim().
Please refer the below question as well
Android: howto parse URL String with spaces to URI object?
Related
I have update from database using set status method when click button to getting error i have send to array list to next activity while getting error
I'm new in android programming
ImageButton ibAddMore = (ImageButton) findViewById(R.id.ibAddMore);
ibAddMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
for (People people : alertList) {//In this Line getting error
if (people.getStatus() == 1) {
db.setStatus(people.getId(), "0");
alertList.add(people);
} else {
db.setStatus(people.getId(), "1");
}
}
Intent intent = new Intent(AlertList.this, AlertListAll.class);
startActivity(intent);
}
}
);
Set Status Method
public int setStatus(String peopleId, String status) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STATUS, status);
return sqLiteDatabase.update(TABLE_PEOPLE, values, ID + "=?",
new String[]{peopleId});
}
Exception:
java.util.ConcurrentModificationException
at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:62)
at com.Jaydeep.alertme.activity.AlertList$1.onClick(AlertList.java:67)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
you can't modify the same collection you are looping on directly. But you can do it using a ListIterator. E.g.
for (ListIterator<People> iterator = alertList.listIterator(); iterator.hasNext(); ) {//In this Line getting error
People people = iterator.next();
if (people.getStatus() == 1) {
db.setStatus(people.getId(), "0");
iterator.add(people);
} else {
db.setStatus(people.getId(), "1");
}
}
You are adding elements to the same list while you are iterating. It's more java than android.
Btw why you want to add the same element again to the list you are iterating thru ?
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
java.lang.NullPointerException occuring
Log-cat says Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
Here's my code:
I'm trying to get jSon data from a server(MySql) database, then displaying it in a list.
public class AllProducts extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> productsList;
private static String url_all_products = "http://server:host.../view.php";
private static final String TAG_SUCCESS="success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
JSONArray products=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
productsList=new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
Exception at new LoadAllProducts().execute();
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String,String,String>
Java.lang.NullPointerException Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
occuring at class LoadAllProducts extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog= new ProgressDialog(AllProducts.this);
pDialog.setMessage("Loading Products....Wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Exception at pDialog.show();
}
#Override
protected String doInBackground(String... params) {
ContentValues param=new ContentValues();
JSONObject json= jParser.makeHttpRequest(url_all_products,"GET",param);
Log.d("All Products: ", json.toString());
java.lang.NullPointerException occuring at Log.d("All Products: ", json.toString());
try{
int success=json.getInt(TAG_SUCCESS);
if(success==1)
{
products = json.getJSONArray(TAG_PRODUCTS);
for(int j=0; j<products.length() ; j++ )
{
JSONObject c = products.getJSONObject(j);
String id=c.getString(TAG_PID);
String name=c.getString(TAG_NAME);
HashMap<String,String> map=new HashMap<String,String>();
map.put(TAG_PID,id);
map.put(TAG_NAME,name);
productsList.add(map);
}
}
else {
Intent i=new Intent(getApplicationContext(),NewProduct.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
}
}
I have a button in my UI to get data from server and show it in a list, as i tap the button, pDialog shows and then the app goes "not responding" and these exceptions occur
Here is the LogCat
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:122)
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ ... 19 more
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
09-03 16:10:40.510 27696-31923/com.example.vashisht.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.vashisht.myapplication, PID: 27696
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.doInBackground(AllProducts.java:76)
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.doInBackground(AllProducts.java:57)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-03 16:10:40.980 27696-27696/com.example.vashisht.myapplication E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.vashisht.myapplication.AllProducts has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{10a4b377 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:382)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.onPreExecute(AllProducts.java:67)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.vashisht.myapplication.AllProducts.onCreate(AllProducts.java:50)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
09-03 16:10:44.250 27696-31923/com.example.vashisht.myapplication D/Process﹕ killProcess, pid=27696
09-03 16:10:44.260 27696-31923/com.example.vashisht.myapplication D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690
this means that the JSONObject json == null. You can check this in code before calling methods on the JSONObject. I guess you dont actually get data when you call the httprequest.
I am trying to populate a listview in my android App (android studio) from a list to which I dynamically added Strings.
First, the list is declared as an attribute of the activity:
private List<String> your_array_list = new ArrayList<String>();
Then, I have the class where the method populatelist() is called. There are other methods called in it, but they all work fine, populatelist() is the only method that gives me an error:
private class SendMessage extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
parse(message);
populatelist();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
And this is the method itself:
public void populatelist() {
// String[] myitems = {"World Weather Online","Open Weather Map","Weather"};
Log.d("Matcher", "Populate! Test 1");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.items,R.id.textting,your_array_list);
Log.d("Matcher", "Populate! Test 2");
ListView list;
Log.d("Matcher", "Populate! Test 3");
list = (ListView) findViewById(R.id.services);
Log.d("Matcher", "Populate! Test 4");
list.setAdapter(adapter);
Log.d("Matcher", "Populate! Test 5");
}
All the logs print except the last one "Test 5". When I run my app, I get the following error:
07-19 21:13:32.399 1575-1591/com.example.othmane.servicefinder E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.example.othmane.servicefinder, PID: 1575
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6247)
at android.view.ViewRootImpl.focusableViewAvailable(ViewRootImpl.java:2855)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.ViewGroup.focusableViewAvailable(ViewGroup.java:679)
at android.view.View.setFlags(View.java:9603)
at android.view.View.setFocusableInTouchMode(View.java:6741)
at android.widget.AdapterView.checkFocus(AdapterView.java:722)
at android.widget.ListView.setAdapter(ListView.java:488)
at com.example.othmane.servicefinder.MainActivity.populatelist(MainActivity.java:277)
at com.example.othmane.servicefinder.MainActivity$SendMessage.doInBackground(MainActivity.java:100)
at com.example.othmane.servicefinder.MainActivity$SendMessage.doInBackground(MainActivity.java:67)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Does anyone see any mistake of how I try to populate the list ? I followed a tutorial to do it, but I don't know why it does not work.
Read the logcat and you will see the answer:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at
The error is caused by you are trying to populate view in the background thread. In order to perform work in the main thread, you need to call onPostExecute method.
Here is the example from one of my app:
public class FetchArtistData extends AsyncTask<String,Void, List<Artist>> {
private static final String TAG="FetchArtistData";
#Override
protected List<Artist> doInBackground(String... params) {
SpotifyApi api=new SpotifyApi();
SpotifyService spotify=api.getService();
ArtistsPager results=spotify.searchArtists(params[0]);
List<Artist> list=results.artists.items;
Log.d(TAG, list.toString());
return list;
}
#Override
protected void onPostExecute(List<Artist> artists) {
mArtistList=(ArrayList<Artist>)artists;
Log.d(TAG,Integer.toString(mArtistList.size()));
updateAdapter(mArtistList);
}
}
Noticed that I update the view in onPostExecute.
i m new in android and trying to make simple program that can print variable in AsyncTask Class
here is my code
int a,b,c;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
a =10;
b=10;
c=a+b;
Context ctx = null;
show(c, ctx );
return null;
}
public void show(int c2 ,Context c) {
// TODO Auto-generated method stub
Toast.makeText(c, "AsyncTask classs + c2 ", Toast.LENGTH_SHORT).show();
}
after running this program , i m getting run time Error
here us LogCat file view
Process: com.example.asycclass, PID: 2539
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:327)
at android.widget.Toast.<init>(Toast.java:92)
at android.widget.Toast.makeText(Toast.java:241)
at com.example.asycclass.MainActivity$AttemptLogin.show(MainActivity.java:74)
at com.example.asycclass.MainActivity$AttemptLogin.doInBackground(MainActivity.java:65)
at com.example.asycclass.MainActivity$AttemptLogin.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
Move your show Toast code inside runOnUiThread like :
runOnUiThread(new Runnable() {
#Override
public void run() {
show(c, ctx );
}
});
I guess that the problem is that you're trying to create a Toast not from the main thread.
You must create a handler and Runnable for that and use handler.post()
For example
Runnable showToast = new Runnable() {
public void run() {
// Create your Toast here or whatever you want
}
}
I have a working code now with my thesis but I decided to clean it up using functions/methods/objects (not really sure what to call them) but after organizing them, my app crashes everytime i start it. I dont really know what the problem is.
Main Screen shows Start and Exit Button. When I press START, the app says "Unfortunately thesis has stopped".
My code goes like this:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.items, menu);
View v = (View) menu.findItem(R.id.search).getActionView();
final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String curtextArray = txtSearch.getText().toString();
char[] curletters = curtextArray.toCharArray();
char[] curenhancedLetters = curtextArray.toCharArray();
//probably, problem here on Stemming stem
Stemming stem = new Stemming(curtextArray, curletters, curenhancedLetters);
AsyncTaskRunner newTask = new AsyncTaskRunner(enhancedStem);
// and probably, problem is here on the stem.<x process>;
stem.removeApostrophe();
stem.vowelMarking();
stem.shortSyllable();
if (continueStem == 1){
stem.region1();
stem.region2();
stem.shortWord();
stem.step0();
stem.step1a();
stem.step1b();
newTask.execute();
}
return false;
};
});
return super.onCreateOptionsMenu(menu);
}
Here's my Stemming Class
public class Stemming {
String textArray;
char[] letters;
char[] enhancedLetters;
public Stemming (String curtextArray, char[] curletters, char[] curenhancedLetters){
this.textArray = curtextArray;
this.letters = curletters;
this.enhancedLetters = curenhancedLetters;
}
public Stemming(){
}
public void removeApostrophe(){
...processes here
}
public void vowelMarking(){
...processes here
}
public void shortSyllable(){
...processes here
}
public void region1(){
...processes here
}
public void region2(){
...processes here
}
public void shortWord(){
...processes here
}
public void step0(){
...processes here
}
public void step1a(){
...processes here
}
public void step1b(){
...processes here
}
}
}
I have a theory on why it crashes. Is this method possible? (pseudocode):
public class Stemming {
String result;
String sample = "A A A A A";
public void changeAtoB{
//do process to convert all As to Bs making String sample = "B B B B B"
result = sample;
}
public void changeBtoC{
//do process to convert all Bs to Cs making String result = "C C C C C"
result = result;
}
... so on {
}
}
What I did was process the string in a straight manner without doing any variable declarations (my variables are declared globally) or initializations. and I also did not put any return statements.
My code used to work when It was still without those functions/methods/objects.
Sorry about my long post. Don't know how to explain it better. I hope you help me. Thank you in Advance!
LOGCAT:
>E/AndroidRuntime(11007): FATAL EXCEPTION: main
E/AndroidRuntime(11007): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.atienzaerni.thesis/com.atienzaerni.thesis.secondactivity}: java.lang.NullPointerException
E/AndroidRuntime(11007): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
E/AndroidRuntime(11007): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
E/AndroidRuntime(11007): at android.app.ActivityThread.access$600(ActivityThread.java:127)
E/AndroidRuntime(11007): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
E/AndroidRuntime(11007): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(11007): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(11007): at android.app.ActivityThread.main(ActivityThread.java:4441)
E/AndroidRuntime(11007): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(11007): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(11007): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime(11007): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime(11007): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(11007): Caused by: java.lang.NullPointerException
E/AndroidRuntime(11007): at android.app.Activity.findViewById(Activity.java:1794)
E/AndroidRuntime(11007): at com.atienzaerni.thesis.secondactivity.<init>(secondactivity.java:54)
E/AndroidRuntime(11007): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(11007): at java.lang.Class.newInstance(Class.java:1319)
E/AndroidRuntime(11007): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
E/AndroidRuntime(11007): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
E/AndroidRuntime(11007): ... 11 more
I/Process(11007): Sending signal. PID: 11007 SIG: 9
(I'm using my phone by the way. Not an emulator. If this makes a difference)
It looks like you are getting a NullPointerException because v is null at this line:
final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
This is probably caused by null being returned from the menu items action view here:
View v = (View) menu.findItem(R.id.search).getActionView();
You should either set the action view in code and not call getActionView or make sure you have a proper action view set in the menu XML. Without seeing your menu XML it's hard to tell if the problem lies in the XML.