NullPointerException error in Android: Unable to instantiate - java

Hello Everyone!
I am having a hard-time in correcting this error that I am facing while developing an android app. I tried to run in an emulator, but it crashes and gives the nullpointerexception error. Then, I made a new project and from scratch copied those files into a new project, and still the same error. Then, I made a part of the app into a new project, and still it gives the same error.
The error is something to do with launching the activity the I am using.
Below are the given necessary files, I hope someone can guide me to the right direction and tell what mistake am I doing. Thanks alot!
DISPLAYPOINTS.JAVA
package com.example.safedrive;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.text.Html;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayPoints extends Activity {
String name = "Ammaar";
TextView display_points;
Button btn_start = (Button) findViewById(R.id.btnStart); //Start Button Variable
String displayPoints;
InputStream is=null;
String result=null;
String line=null;
int points;
int code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_points);
TextView lblName = (TextView) findViewById(R.id.lblName);
display_points = (TextView) findViewById(R.id.lblCurrPoints); //POINTS TO DISPLAY IN
lblName.setText(Html.fromHtml("Welcome <b>" + name + "! </b>"));
new Insert().execute();
btn_start.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//MainScreen.IsStarted=true;
//SpeedPoints start = new SpeedPoints();
//Intent i = new Intent(getApplicationContext(), SpeedPoints.class);
//startActivity(i);
Toast.makeText(getApplicationContext(), "The app has started monitoring your drive...",
Toast.LENGTH_LONG).show();
//start.startAnimation();
}
});
}
class Insert extends AsyncTask<String, Void, String> {
// Do the long-running work in here
protected String doInBackground(String... args) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("fname", name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ammar123.net84.net/capstone/displayPoints.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
points=(json_data.getInt("pointss"));
displayPoints = Integer.toString(points);
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
return displayPoints;
}//End of doInBackground method
protected void onPostExecute(String displaypoints) {
display_points.setText(displayPoints);
Toast.makeText(getBaseContext(), "Points Retrieved!",
Toast.LENGTH_SHORT).show();
}//End of onPostExecute
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_points, 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);
}
}
MANIFEST FILE
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.safedrive"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.safedrive.DisplayPoints"
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>
LOGCAT ERRORS:
06-09 18:52:55.467: ERROR/ResourceType(87): Style contains key with bad entry: 0x01010479
06-09 18:52:56.567: ERROR/AndroidRuntime(771): FATAL EXCEPTION: main
06-09 18:52:56.567: ERROR/AndroidRuntime(771): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.safedrive/com.example.safedrive.DisplayPoints}: java.lang.NullPointerException
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1879)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.access$600(ActivityThread.java:122)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.os.Handler.dispatchMessage(Handler.java:99)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.os.Looper.loop(Looper.java:137)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.main(ActivityThread.java:4340)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at java.lang.reflect.Method.invokeNative(Native Method)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at java.lang.reflect.Method.invoke(Method.java:511)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at dalvik.system.NativeStart.main(Native Method)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): Caused by: java.lang.NullPointerException
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.Activity.findViewById(Activity.java:1794)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at com.example.safedrive.DisplayPoints.<init>(DisplayPoints.java:34)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at java.lang.Class.newInstanceImpl(Native Method)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at java.lang.Class.newInstance(Class.java:1319)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): ... 11 more

put this line
btn_start = (Button) findViewById(R.id.btnStart); //Start Button Variable
after
setContentView(R.layout.display_points);
findViewById is only possible after the layout is defined.

Related

How to connect an Android application to a MySQL database?

I am very new at programming Android applications, So please help me.
I want to connect my application to a MySQL database.
But I get an error that crashes the application. Here is the error in LogCat:
07-26 12:32:47.785: E/AndroidRuntime(276): FATAL EXCEPTION: main
07-26 12:32:47.785: E/AndroidRuntime(276): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.massar_parent/com.example.parent.MainActivity}: java.lang.NullPointerException
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.os.Handler.dispatchMessage(Handler.java:99)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.os.Looper.loop(Looper.java:123)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-26 12:32:47.785: E/AndroidRuntime(276): at java.lang.reflect.Method.invokeNative(Native Method)
07-26 12:32:47.785: E/AndroidRuntime(276): at java.lang.reflect.Method.invoke(Method.java:521)
07-26 12:32:47.785: E/AndroidRuntime(276): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-26 12:32:47.785: E/AndroidRuntime(276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-26 12:32:47.785: E/AndroidRuntime(276): at dalvik.system.NativeStart.main(Native Method)
07-26 12:32:47.785: E/AndroidRuntime(276): Caused by: java.lang.NullPointerException
07-26 12:32:47.785: E/AndroidRuntime(276): at com.example.massar_parent.MainActivity.onCreate(MainActivity.java:44)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-26 12:32:47.785: E/AndroidRuntime(276): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
And the code in MainActivity.java
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
//private TextView texte = null;
TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt.setText("Connexion...");
// Appeler la méthode pour récupérer les données JSON
txt.setText(getServerData(strURL));
}
// Mettre l'adresse du script PHP
// Attention localhost ou 127.0.0.1 ne fonctionnent pas. Mettre l'adresse IP
// local.
public static final String strURL = "http://localhost/massar/connection.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("NomEleve", "L"));
// Envoie de la commande http
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convertion de la requête en string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// Parse les données JSON
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
// Affichage ID_ville et Nom_ville dans le LogCat
Log.i("log_tag", "CNE: " + json_data.getInt("CNE") + ", NomEleve: "
+ json_data.getString("NomEleve"));
// Résultats de la requête
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
And here is the code AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.massar_parent"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<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>
I hope someone can help :/
There are two mistakes I can see:
TextView is not initialized. Do you know findViewById()?
You have made a web call directly on main UI thread which would cause an issue!
You have a field txt:
TextView txt;
which is declared, but it is never set to a value. Therefore, when you try to use it here:
txt.setText("Connexion...");
it throws an exception because it still has the value null.
If you have declared the TextView in your layout (e.g. with <TextView android:id="#+id/the_identifier_of_your_textview"), you need to assign it like this, immediately after calling setContentView:
txt = (TextView)this.FindViewById(R.id.the_identifier_of_your_textview);

Android Studio configuration still incorrect along with app stopping in emulator

I am trying to build a TTS for a school project. When I click run it says configuration still incorrect. However, the emulator still comes up, but when I click on the app to run it says it has stopped. I am very new to Android Studio so sorry if this seems like a dumb question. Here is what I have:
package com.example.james.texttospeech;
import android.os.Bundle;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import java.util.Locale;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
//TTS object
private TextToSpeech myTTS;
//status check code
private int MY_DATA_CHECK_CODE = 0;
//create the Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get a reference to the button element listed in the XML layout
Button speakButton = (Button)findViewById(R.id.speak);
//listen for clicks
speakButton.setOnClickListener(this);
//check for TTS data
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
}
//respond to button clicks
public void onClick(View v) {
//get the text entered
EditText enteredText = (EditText)findViewById(R.id.enter);
String words = enteredText.getText().toString();
speakWords(words);
}
//speak the user text
private void speakWords(String speech) {
//speak straight away
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
//act on result of TTS data check
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
//the user has the necessary data - create the TTS
myTTS = new TextToSpeech(this, this);
}
else {
//no data - install it now
Intent installTTSIntent = new Intent();
installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
}
//setup TTS
public void onInit(int initStatus) {
//check for successful instantiation
if (initStatus == TextToSpeech.SUCCESS) {
if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.US);
}
else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
}
}
}
Here is the logcat I know it's not pretty:
03-05 00:15:46.389 2264-2264/com.example.james.texttospeech D/AndroidRuntime﹕ Shutting down VM
--------- beginning of crash
03-05 00:15:46.390 2264-2264/com.example.james.texttospeech E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.james.texttospeech, PID: 2264
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.james.texttospeech/com.example.james.texttospeech.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.james.texttospeech.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.james.texttospeech-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
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.lang.ClassNotFoundException: Didn't find class "com.example.james.texttospeech.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.james.texttospeech-2/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            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)
Suppressed: java.lang.ClassNotFoundException: com.example.james.texttospeech.MainActivity
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
Here is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.james.texttospeech" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Unable to instantiate activity ComponentInfo .. java.lang.NullPointerException

I'm trying to run a simple app using volley and a custom header, it builds with no error, I'm running it directly in my smartphone, but when the app start I get the following log:
06-24 16:35:35.653 1380-1380/com.rep E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.rep, PID: 1380
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.rep/com.rep.app.principal.InicioActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2135)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getCacheDir(ContextWrapper.java:230)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:43)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at com.representemais.app.principal.InicioActivity.<init>(InicioActivity.java:86)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1084)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2126)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.access$800(ActivityThread.java:139)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5102)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
that's the InicioActivity:
package com.rep.app.principal;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.rep.R;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class InicioActivity extends SherlockFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AutenticacaoLocalTask mAutenticacaoLocalTask = new AutenticacaoLocalTask();
mAutenticacaoLocalTask.execute((Void) null);
}
private TextView txtDisplay;
RequestQueue queue = Volley.newRequestQueue(this);
public class AutenticacaoLocalTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
txtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://192.168.1.15/rep-api/api/clients";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
txtDisplay.setText("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-API-TOKEN", "99KI9Gj68CgCf70deM22Ka64chef2C40Gm2lFJ2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8");
return headers;
}
};
queue.add(jsonObjReq);
return true;
} catch (Exception e) {
Log.e("RM", e.getMessage());
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
}
#Override
protected void onCancelled() {
}
}
}
and the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rep"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name=".app.principal.InicioActivity"
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=".app.login.LoginActivity"
android:configChanges="keyboardHidden"
android:label="#string/app_name">
</activity>
<activity
android:name=".app.principal.MainActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.cliente.ClienteDetalheActivity"
android:label="#string/app_name"></activity>
<activity android:name=".app.login.LoginTelaBloqueada"
android:label="#string/app_name"></activity>
</application>
</manifest>
Initialize your RequestQueue, using Volley.newRequestQueue(this);, in onCreate() after the super.onCreate() call. You are trying to use your Activity from an initializer, which frequently causes problems like this.
Step #1: Replace:
RequestQueue queue = Volley.newRequestQueue(this);
with:
RequestQueue queue = null;
Step #2: Change your onCreate() to be:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
queue=Volley.newRequestQueue(this);
AutenticacaoLocalTask mAutenticacaoLocalTask = new AutenticacaoLocalTask();
mAutenticacaoLocalTask.execute((Void) null);
}

Unable to Instantiate ComponentInfo NullPointerException

I'm pretty new to Android development so I'm sure this is going to turn out to be something stupid that I've missed, but I have two activities: StartScreen and Map. StartScreen is just simple text and a button, which is supposed to then take you to the Map activity.
I've already tried reducing the Map activity down to almost nothing, and I'm sure it's nothing in there that's causing the error, but I just can't figure out what is.
This is the logcat output for the error, it happens when I press the button linking the two activities:
04-28 20:40:24.097: E/AndroidRuntime(13458): FATAL EXCEPTION: main
04-28 20:40:24.097: E/AndroidRuntime(13458): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.rr.freespace/com.rr.freespace.Map}: java.lang.NullPointerException
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2229)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.access$600(ActivityThread.java:139)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1261)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.os.Looper.loop(Looper.java:154)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.main(ActivityThread.java:4945)
04-28 20:40:24.097: E/AndroidRuntime(13458): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 20:40:24.097: E/AndroidRuntime(13458): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 20:40:24.097: E/AndroidRuntime(13458): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-28 20:40:24.097: E/AndroidRuntime(13458): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-28 20:40:24.097: E/AndroidRuntime(13458): at dalvik.system.NativeStart.main(Native Method)
04-28 20:40:24.097: E/AndroidRuntime(13458): Caused by: java.lang.NullPointerException
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.content.ComponentName.<init>(ComponentName.java:75)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.content.Intent.<init>(Intent.java:3475)
04-28 20:40:24.097: E/AndroidRuntime(13458): at com.rr.freespace.Map.<init>(Map.java:12)
04-28 20:40:24.097: E/AndroidRuntime(13458): at java.lang.Class.newInstanceImpl(Native Method)
04-28 20:40:24.097: E/AndroidRuntime(13458): at java.lang.Class.newInstance(Class.java:1319)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.Instrumentation.newActivity(Instrumentation.java:1039)
04-28 20:40:24.097: E/AndroidRuntime(13458): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
Here's my StartScreen.java:
package com.rr.freespace;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class StartScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
}
public void doIt(View view) { // Do something in response to button }
Intent intent = new Intent(this, Map.class);
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.start_screen, menu);
return true;
}
}
The activity_start_screen.xml layout file:
<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=".StartScreen" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="180dp"
android:text="#string/hometext2"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:text="#string/doit"
android:onClick="doIt" />
</RelativeLayout>
And finally, the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rr.freespace"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<permission
android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.rr.freespace.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<uses-library android:name="com.google.android.maps" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBaoeVjdRY312vJ5KMLXxmzpKHhPiYqASo"/>
<activity
android:name="com.rr.freespace.StartScreen"
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.rr.freespace.Map"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
I hope someone can figure out what's going on here, because I can't! Cheers!
EDIT: here's the map.java code, there may be more errors in here that I haven't got to yet, because I hacked most of this together yesterday before I had access to an android device:
package com.rr.freespace;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
public class Map extends Activity {
final Context context = this;
Intent goback = new Intent(this, StartScreen.class);
protected LocationManager locationManager;
protected LocationListener listener;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
AlertDialog.Builder gpssettings = new AlertDialog.Builder(context);
gpssettings.setMessage(R.string.gpstext)
.setTitle(R.string.gpstitle);
gpssettings.setPositiveButton(R.string.gpsok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
enableLocationSettings();
}
});
gpssettings.setNegativeButton(R.string.gpscancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
startActivity(goback);
}
});
}
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
GoogleMapOptions options = new GoogleMapOptions();
options.mapType(GoogleMap.MAP_TYPE_NORMAL)
.compassEnabled(false)
.rotateGesturesEnabled(false)
.tiltGesturesEnabled(false);
//Get GPS data
final LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// A new location update is received. Do something useful with it. Update the UI with
// the location update.
final LatLng position = new LatLng(location.getLatitude(),location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000, // 10-second interval.
5, // 5 meters.
listener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
private void enableLocationSettings() {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
protected void onStop() {
super.onStop();
locationManager.removeUpdates(listener);
}
}
Intent goback = new Intent(this, StartScreen.class);
that causes an issue.
You can't use "this" here, best to create intents just before using them.
But if You would like to have it as soon as possible do it in onCreate.

Error while running the android project in eclipse run time error

05-05 14:32:25.210: ERROR/AndroidRuntime(551): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.org.pc/com.org.pc.Login}: java.lang.NullPointerException
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.os.Handler.dispatchMessage(Handler.java:99)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.os.Looper.loop(Looper.java:123)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.main(ActivityThread.java:4363)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at java.lang.reflect.Method.invokeNative(Native Method)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at java.lang.reflect.Method.invoke(Method.java:521)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at dalvik.system.NativeStart.main(Native Method)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): Caused by: java.lang.NullPointerException
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at com.org.pc.Login.loginDetails(Login.java:116)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at com.org.pc.Login.onCreate(Login.java:54)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
the code is :
package com.org.pc;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
public class Login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Login","Reached");
Log.i("Login","View set");
Bitmap bitmap = (Bitmap) this.getIntent().getParcelableExtra("BitmapImage");
if(bitmap==null)
Log.v("Sdrawable","null");
else
Log.v("Sdrawable","not null");
loginDetails();
setContentView(R.layout.view);
ImageView viewBitmap = (ImageView)findViewById(R.id.bitmapview);
viewBitmap.setImageBitmap(bitmap);
Button login=(Button) findViewById(R.id.login);
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
username = pref.getString(PREF_USERNAME, null);
password = pref.getString(PREF_PASSWORD, null);
if(username != null && password != null)
{
Log.v("username",username);
//user.setText(username);
//pass.setText(password);
}
login.setOnClickListener(new Button.OnClickListener()
{
public void onClick (View v)
{
setContentView(R.layout.home);
}
});
}
public static final String PREFS_NAME = "PrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";
public String username = null;
public String password = null;
//EditText user = (EditText)findViewById(R.id.username);
//EditText pass = (EditText)findViewById(R.id.password);
public void loginDetails()
{
if (username == null || password == null)
{
// username = user.getText().toString();
// password = pass.getText().toString();
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://69.10.60.88:88/BZLogin.aspx");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", "abdul"));
nameValuePairs.add(new BasicNameValuePair("password", "abdul"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
CheckBox cb = (CheckBox)findViewById(R.id.remember);
if ( cb.isChecked() )
{
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, username)
.putString(PREF_PASSWORD, password)
.commit();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
You're calling loginDetails() before you have inflated your layout to the activity. So, no ui elements exist. call setContentView() before you call findViewById().
You called CheckBox cb = (CheckBox)findViewById(R.id.remember) before setContentView(R.layout.view). That's may be why.
Call loginDetails() after setContentView(R.layout.view).

Categories