1

I know this question has been asked many times as I did my research. In fact, I checked the following posts but they haven't helped so I'm posting my question:

java.lang.RuntimeException: Unable to start activity ComponentInfo

Android cannot start Activity - java.lang.RuntimeException: Unable to start activity ComponentInfo

Android unable to start activity componentinfo error when calling another class

The basic idea of my code is to obtain a string from another device, tokenize it based on a delimiter and send it the login activity. So far the tokenization works, but the error lies in opening the activity page, so I suspect the error is in Login.java but I can't figure out what it is. Android Studio itself doesn't show any errors during compilation. Also, yet I did include everything in the manifest file.

Here is the logcat:

03-23 13:41:04.528  24068-24068/com.example.home.mysqltest I/message﹕ 1
03-23 13:41:04.528  24068-24068/com.example.home.mysqltest I/message﹕ b
03-23 13:41:04.528  24068-24068/com.example.home.mysqltest I/message﹕ c
03-23 13:41:04.701  24068-24068/com.example.home.mysqltest D/AndroidRuntime﹕                        
Shutting down VM
03-23 13:41:04.702  24068-24068/com.example.home.mysqltest E/AndroidRuntime﹕   
FATAL EXCEPTION: main
Process: com.example.home.mysqltest, PID: 24068
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.home.mysqltest/com.example.home.mysqltest.login}: java.util.NoSuchElementException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        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:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
 Caused by: java.util.NoSuchElementException

Here is the login.java

        package com.example.home.mysqltest;


    import java.util.ArrayList;
    import java.util.List;
    import java.util.StringTokenizer;

    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

public class login extends Activity implements OnClickListener{

private EditText user, pass;
private String user1,pass1;
private Button mSubmit;
String fileno;
String name;


// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//php login script location:

//localhost :
//testing on your device
//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";

//testing on Emulator:
private static final String LOGIN_URL = "http://nfcquickbanker.esy.es/WebServer/login.php";

//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";

//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    //setup input
    fileno=(String)MainActivity.uni.nextElement().toString();
    user1 = (String) MainActivity.uni.nextElement().toString();
    pass1 = (String)MainActivity.uni.nextElement().toString();

    user = (EditText)findViewById(R.id.username);
    user.setText(user1, TextView.BufferType.EDITABLE);
    pass = (EditText)findViewById(R.id.password);
    pass.setText(pass1, TextView.BufferType.EDITABLE);



    //setup buttons
    mSubmit = (Button)findViewById(R.id.login);

    //register listeners
    mSubmit.setOnClickListener(this);


}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
        case R.id.login:
            new AttemptLogin().execute();
            break;
        default:
            break;
    }
}

class AttemptLogin extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(login.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(login.this);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("username", username);
                edit.commit();

                switch (fileno)
                {
                    case "1": name="dd";
                        break;
                    case "2": name="deposit";
                        break;
                    case "3": name="travellerscheck";
                        break;
                    default: break;
                }

                try
                {
                    Class openact = Class.forName("com.example.home.mysqltest." + name);
                    Intent a = new Intent(login.this, openact);
                    startActivity(a);

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

                return json.getString(TAG_MESSAGE);




            }
                else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                Intent a = new Intent(login.this, loginfail.class);
                startActivity(a);
                return json.getString(TAG_MESSAGE);

            }
        }
            catch (JSONException e) {
            e.printStackTrace();
                                    }

        return null;

    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(login.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

 }

Here is the activity that launches initially, it's responsible for getting the string and opening the login activity.

import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;  
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.widget.TextView;
import java.util.*;


public class MainActivity extends Activity {

private TextView mTextView;
static StringTokenizer uni;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTextView = (TextView) findViewById(R.id.text_view);
}

@Override
protected void onResume(){
    super.onResume();
    Intent intent = getIntent();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
        Parcelable[] rawMessages = intent.getParcelableArrayExtra(
        NfcAdapter.EXTRA_NDEF_MESSAGES);

        NdefMessage message = (NdefMessage) rawMessages[0]; // only one message transferred
        uni=new StringTokenizer(new String(message.getRecords()[0].getPayload()),"~");

        while(uni.hasMoreElements())
        {
            String s=uni.nextElement().toString();
            Log.i("message",s);

        }
       /* mTextView.setText(new String(message.getRecords()[0].getPayload()));
        Intent i=new Intent(MainActivity.this,login.class);
        finish();
        startActivity(i);
        */
        try
        {
           Intent a = new Intent(MainActivity.this, login.class);
            startActivity(a);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        mTextView.setText(new String(message.getRecords()[0].getPayload()));


    } else

        mTextView.setText("Waiting for NDEF Message");

}
 }
Community
  • 1
  • 1
Light Yagami
  • 321
  • 3
  • 13
  • After some research, I've figured out that the problem has to so with the STRING uni. It is unable to retrieve from the string tokenizer – Light Yagami Mar 23 '15 at 10:14

3 Answers3

0

You are using StringTokenizer so

Replace

while(uni.hasMoreElements())
    {
        String s=uni.nextElement().toString();
        Log.i("message",s);

    }

With

while(uni.hasMoreTokens())
    {
        String s=uni.nextToken().toString();
        Log.i("message",s);

    }
  • Okay, but this doesn't answer my question and I don't have a problem with my tokenizer. It does give out the desired output – Light Yagami Mar 23 '15 at 09:13
0

You should check your manifest.xml file. Have you added a activity tag for 'login' activity.

Gaurav
  • 1,965
  • 2
  • 16
  • 32
0

In login.onCreate() you do:

//setup input
fileno=(String)MainActivity.uni.nextElement().toString();
user1 = (String) MainActivity.uni.nextElement().toString();
pass1 = (String)MainActivity.uni.nextElement().toString();

one of these is failing. Any call to nextElement() can throw NoSuchElementException, which will cause this problem.

You need to code more robustly. Wrap this stuff in try/catch or validate your input before trying to parse it.

Also, if you look further in your stack trace it will tell you exactly where the problem is occuring. You cut off your stack trace in your post just at the good part.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • ` while(uni.hasMoreElements()) { String s=uni.nextElement().toString(); Log.i("message",s); }` I was getting the NullPointerException since I was traversing along a string and printing it out, and it would reach the end by the time I tried to put the strings contents into a variable – Light Yagami Apr 08 '15 at 13:32