List<MyStructure> error: App crashes, No idea why - java

I've built some class named "item", here is it: (thats the whole code)
public class item {
private int id;
private String title;
private String desc;
private double lat;
private double lon;
private String pub;
private int p;
private int n;
public item(int id, String title, String desc, double lat, double lon, String pub, int p, int n) {
super();
this.id = id;
this.title = title;
this.desc = desc;
this.lat = lat;
this.lon = lon;
this.pub = pub;
this.p = p;
this.n = n;
}
Now I have to make a List<item> and add() "item"s to it, but for some reason my application crushes.
Thats the Activity:
public class MainActivity extends Activity {
List<item> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
LOGCAT:
08-10 16:32:46.710: D/AndroidRuntime(2934): Shutting down VM
08-10 16:32:46.710: W/dalvikvm(2934): threadid=1: thread exiting with uncaught exception (group=0x41a0a930)
08-10 16:32:46.777: E/AndroidRuntime(2934): FATAL EXCEPTION: main
08-10 16:32:46.777: E/AndroidRuntime(2934): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testitems/com.example.testitems.MainActivity}: java.lang.NullPointerException
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.access$600(ActivityThread.java:153)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.os.Looper.loop(Looper.java:137)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.main(ActivityThread.java:5227)
08-10 16:32:46.777: E/AndroidRuntime(2934): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 16:32:46.777: E/AndroidRuntime(2934): at java.lang.reflect.Method.invoke(Method.java:511)
08-10 16:32:46.777: E/AndroidRuntime(2934): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
08-10 16:32:46.777: E/AndroidRuntime(2934): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
08-10 16:32:46.777: E/AndroidRuntime(2934): at dalvik.system.NativeStart.main(Native Method)
08-10 16:32:46.777: E/AndroidRuntime(2934): Caused by: java.lang.NullPointerException
08-10 16:32:46.777: E/AndroidRuntime(2934): at com.example.testitems.MainActivity.onCreate(MainActivity.java:18)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.Activity.performCreate(Activity.java:5104)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262)
08-10 16:32:46.777: E/AndroidRuntime(2934): ... 11 more
Appreciate your help guys!

Initialize your markers list
List<item> markers=new ArrayList<item>();

try this
public class MainActivity extends Activity {
ArrayList<item> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}

You have to initialize the list before you use it.
setContentView(R.layout.activity_main);
List<item> markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);

Any object should be initialized before using its methods, however you seem to forgot this step before adding data in your list. Initialize markers before adding data in it.
List<item> markers=new ArrayList<item>();

In the code you have not initialize the arraylist object to remove these errors
see the following steps mention below:
First allocate memory to the Arraylist object like this
public class MainActivity extends Activity {
ArrayList markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
Secondly to handle the error use the try and the catch block .
public class MainActivity extends Activity {
ArrayList markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
catch(Exception e)
{
//Write to android ddms logger.
or
make a Toast Message
}
}
Free the resources which has been intialize like arraylist etc.
By putting finally block after the catch Block.

Related

ASyncTask with progressdialog and button

I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}

"Application has stopped" when filling ListView

Well, I have this problem and I don't know why because Eclipse doesn't tells me which the error is. I'm a beginner in Java and I don't know what to do. Here's my code:
package com.example.asado;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class ListaActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.listas);
addListenerOnButton();
final ListView listview = (ListView) findViewById(R.id.lista_compra);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux",
"OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2",
"Android", "iPhone", "WindowsMobile" };
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN) #Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0)
.withEndAction(new Runnable() {
#Override
public void run() {
list.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
public void addListenerOnButton() {
ImageButton compra = (ImageButton) findViewById(R.id.compra);
// Listening to Login Screen link
compra.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Cierro la ventana
// cambio de pesta�a
finish();
}
});
}
}
It's a bit messy but the error is that when this layout is about to open, I get the error "Unfortunately the application has stopped". Thanks in advance.
These are the Errors at Logcat:
07-23 16:05:06.509: E/AndroidRuntime(8794): FATAL EXCEPTION: main
07-23 16:05:06.509: E/AndroidRuntime(8794): Process: com.example.asado, PID: 8794
07-23 16:05:06.509: E/AndroidRuntime(8794): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asado/com.example.asado.ListaActivity}: java.lang.NullPointerException
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.access$800(ActivityThread.java:139)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.os.Handler.dispatchMessage(Handler.java:102)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.os.Looper.loop(Looper.java:136)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.main(ActivityThread.java:5102)
07-23 16:05:06.509: E/AndroidRuntime(8794): at java.lang.reflect.Method.invokeNative(Native Method)
07-23 16:05:06.509: E/AndroidRuntime(8794): at java.lang.reflect.Method.invoke(Method.java:515)
07-23 16:05:06.509: E/AndroidRuntime(8794): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-23 16:05:06.509: E/AndroidRuntime(8794): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-23 16:05:06.509: E/AndroidRuntime(8794): at dalvik.system.NativeStart.main(Native Method)
07-23 16:05:06.509: E/AndroidRuntime(8794): Caused by: java.lang.NullPointerException
07-23 16:05:06.509: E/AndroidRuntime(8794): at com.example.asado.ListaActivity.onCreate(ListaActivity.java:39)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.Activity.performCreate(Activity.java:5248)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
07-23 16:05:06.509: E/AndroidRuntime(8794): ... 11 more
Try to replace:
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
with this:
#Override
public long getItemId(int position) {
return position;
}
ListActivity's line 39 has nullpointer see if list is set correctly, if you look at this example List works better if its id is created #android:id/list instead of created by giving id value.
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

Google Analytics Android error java.lang.NullPointerException

I'm trying to work on Google Analytics for Androi. I get the message, and I'm following the advanced configuration of Android Analytics in Google Android SDK.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.secondapp/com.example.secondapp.MainActivity}:
java.lang.NullPointerException
And I get this error:
01-02 15:39:38.410: D/AndroidRuntime(1338): Shutting down VM
01-02 15:39:38.410: W/dalvikvm(1338): threadid=1: thread exiting with uncaught exception (group=0xb1ab7ba8)
01-02 15:39:38.420: E/AndroidRuntime(1338): FATAL EXCEPTION: main
01-02 15:39:38.420: E/AndroidRuntime(1338): Process: com.example.secondapp, PID: 1338
01-02 15:39:38.420: E/AndroidRuntime(1338): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.secondapp/com.example.secondapp.MainActivity}: java.lang.NullPointerException
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.os.Handler.dispatchMessage(Handler.java:102)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.os.Looper.loop(Looper.java:136)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-02 15:39:38.420: E/AndroidRuntime(1338): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 15:39:38.420: E/AndroidRuntime(1338): at java.lang.reflect.Method.invoke(Method.java:515)
01-02 15:39:38.420: E/AndroidRuntime(1338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-02 15:39:38.420: E/AndroidRuntime(1338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-02 15:39:38.420: E/AndroidRuntime(1338): at dalvik.system.NativeStart.main(Native Method)
01-02 15:39:38.420: E/AndroidRuntime(1338): Caused by: java.lang.NullPointerException
01-02 15:39:38.420: E/AndroidRuntime(1338): at com.example.secondapp.MainActivity.onCreate(MainActivity.java:24)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.Activity.performCreate(Activity.java:5231)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-02 15:39:38.420: E/AndroidRuntime(1338): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
01-02 15:39:38.420: E/AndroidRuntime(1338): ... 11 more
Here is my code for SecondAppApplication, which has similarities to the android docs:
public class SecondAppApplication extends Application {
private static GoogleAnalytics mGa;
private static Tracker mTracker;
private static final String GA_PROPERTY_ID = "UA-XXXXXXXX-1";
private static final int GA_DISPATCH_PERIOD = 30;
private static final boolean GA_IS_DRY_RUN = false;
private static final LogLevel GA_LOG_VERBOSITY = LogLevel.INFO;
private static final String TRACKING_PREF_KEY = "trackingPreferences";
#SuppressWarnings("deprecation")
private void initializeGa() {
mGa = GoogleAnalytics.getInstance(this);
mTracker = mGa.getTracker(GA_PROPERTY_ID);
GAServiceManager.getInstance().setLocalDispatchPeriod(GA_DISPATCH_PERIOD);
mGa.setDryRun(GA_IS_DRY_RUN);
mGa.getLogger().setLogLevel(GA_LOG_VERBOSITY);
SharedPreferences userPrefs = PreferenceManager.getDefaultSharedPreferences(this);
userPrefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(TRACKING_PREF_KEY)) {
GoogleAnalytics.getInstance(getApplicationContext()).setAppOptOut(sharedPreferences.getBoolean(key, false));
}
}
});
}
#Override
public void onCreate() {
super.onCreate();
initializeGa();
}
public static Tracker getGaTracker() {
return mTracker;
}
public static GoogleAnalytics getGaInstance() {
return mGa;
}
}
Here is my MainActivity class:
public class MainActivity extends Activity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private static final String SCREEN_LABEL = "Main Screen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SecondAppApplication.getGaTracker().set(Fields.SCREEN_NAME,SCREEN_LABEL);
setContentView(R.layout.main);
}
#Override
public void onStart() {
super.onStart();
SecondAppApplication.getGaTracker().send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openSearch() {
}
public void openSettings() {
}
public void sendMessage(View view) {
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Why does java.lang.NullPointerException exists, and/or how would I solve this?
Do I need to declare initializeGa() again inside MainActivity or AndroidManifest.xml?
It looks to me like:
SecondAppApplication.getGaTracker().set(Fields.SCREEN_NAME,SCREEN_LABEL);
Is probably calling the set method on a null object, because your accessing statically without initializing it first. This almost looks like you were trying to do a singleton or something...
I would change your code to:
public static Tracker getGaTracker() {
if(mTracker ==null) {
initialize();
}
return mTracker;
}
The problem of course being that since you're doing this statically you wont have a context to pass.... I think you may need to reorganize the project a bit.
Check out this:
Android: Persist object across activities
I found out that the AndroidManifest.xml application should contain the correct android.name.
In this case, android.name="com.example.secondapplication.SecondAppApplication"

Unable to retrieve the value of textfield

i am the newbee in Android Development.
I had developed an app contains a login, the credentials must be passed in the text field and later it will call a webservice.
I am facing the issue as user and password is not getting copied at the required position.
Please help me out.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity implements OnClickListener {
EditText txtUserName;
EditText txtPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String user= txtUserName.getText().toString();
String pass= txtPassword.getText().toString();
System.out.println("USERRRR"+user);
System.out.println(pass);
//String user="at#ril.com";
//String pass= "123456";
String accessTokenQry = "{"+
"\"uid\":\""+user+"\","+
"\"password\":\""+pass+"\","+
"\"consumptionDeviceId\":\"fder-et3w-3adw2-2erf\","+
"\"consumptionDeviceName\":\"Samsung Tab\""+
"}";
HttpPost httpPost = new HttpPost("http://devssg01.ril.com:8080/v2/dip/auth/login");
httpPost.setHeader("Content-Type",
"application/json");
httpPost.setHeader("X-API-Key",
"l7xx7914b8704b2d4b029ab9c4b1b9c66dbf");
StringEntity input;
try {
input = new StringEntity(accessTokenQry);
httpPost.setEntity(input);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String text = null;
try {
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
The LogCat Output is:
08-10 01:20:23.977: W/dalvikvm(760): threadid=14: thread exiting with uncaught exception (group=0x414c4700)
08-10 01:20:23.984: E/AndroidRuntime(760): FATAL EXCEPTION: AsyncTask #4
08-10 01:20:23.984: E/AndroidRuntime(760): java.lang.RuntimeException: An error occured while executing doInBackground()
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$3.done(AsyncTask.java:299)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.lang.Thread.run(Thread.java:841)
08-10 01:20:23.984: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:66)
08-10 01:20:23.984: E/AndroidRuntime(760): at com.authorwjf.http_get.Main$LongRunningGetIO.doInBackground(Main.java:1)
08-10 01:20:23.984: E/AndroidRuntime(760): at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-10 01:20:23.984: E/AndroidRuntime(760): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-10 01:20:23.984: E/AndroidRuntime(760): ... 3 more
You are trying to initialize EditTexts before layout loaded.
If you want to get EditText on layout, you must initialize it after layout loaded.
Here is correct code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
use this
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
I suggest following change in your code.
Just write following lines
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
above
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
Move the lines where you get the reference to text views after the setContentView function call:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}
The fact is you need to call setContentView before initializing any widget in your layout because this is the call that "loads" your layout defined in layout_main.xml file into your activity.
Thanks a lot Guyz,
The issue is resolved now.
Special appreciation to JustWork
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
txtUserName=(EditText)this.findViewById(R.id.editText1);
txtPassword=(EditText)this.findViewById(R.id.editText2);
}

Using AsyncTask to display multiple markers on google map

I have a problem again with AsyncTask in Android.
I made a simple AsyncTask class to display multiple markers on a MapView. But starting the activity, there is a NullPointerException - I think this is caused by the MapView...
public class MapDetail extends MapActivity {
// JSON Node names
private static final String TAG_NEWNAME = "name";
private static final String TAG_LONG = "long";
private static final String TAG_LAT = "lat";
// Variablen
private MapController mc;
private List<Overlay> mapOverlays;
private Drawable drawable;
private MapItemizedOverlay itemizedoverlay;
private MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.offers);
// getting intent data
Bundle extras = getIntent().getExtras();
String url = extras.getString("url");
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.marker);
itemizedoverlay = new MapItemizedOverlay(drawable, this);
new MyAsyncTask().execute(url);
}
And this is my AsyncTask:
public class MyAsyncTask extends AsyncTask<String, Void, MapItemizedOverlay > {
#Override
protected MapItemizedOverlay doInBackground(String... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
JSONArray locations = jParser.getJSONArrayFromUrl(params[0]);
for (int i = 0; i < locations.length(); i++) {
JSONObject c;
try {
c = locations.getJSONObject(i);
// Storing each json item in variable
String firma = c.getString(TAG_NEWNAME);
String longitude = c.getString(TAG_LONG);
String latitude = c.getString(TAG_LAT);
System.out.println("Kriege ich daten"+longitude+"und"+latitude);
double x = Double.parseDouble(latitude);
double y = Double.parseDouble(longitude);
GeoPoint point = new GeoPoint((int)(x * 1E6),(int)(y * 1E6) );
OverlayItem overlayitem = new OverlayItem(point, firma, null);
itemizedoverlay.addOverlay(overlayitem);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(itemizedoverlay.toString());
return itemizedoverlay;
}
#Override
protected void onPostExecute(MapItemizedOverlay result) {
mapOverlays.add(result);
mapView.getOverlays().add(result);
LocationManager myLocationManager;
LocationListener myLocationListener;
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,myLocationListener);
GeoPoint initGeoPoint = new GeoPoint( (int)(myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude()*1000000),
(int)(myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude()*1000000));
mc.animateTo(initGeoPoint);
mc.setZoom(6);
mapView.invalidate();
}
}}
My Log:
01-06 19:49:23.703: E/AndroidRuntime(6064): FATAL EXCEPTION: main
01-06 19:49:23.703: E/AndroidRuntime(6064): java.lang.NullPointerException
01-06 19:49:23.703: E/AndroidRuntime(6064): at de.main.MapDetail$MyAsyncTask.onPostExecute(MapDetail.java:150)
01-06 19:49:23.703: E/AndroidRuntime(6064): at de.main.MapDetail$MyAsyncTask.onPostExecute(MapDetail.java:1)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.Handler.dispatchMessage(Handler.java:99)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.os.Looper.loop(Looper.java:137)
01-06 19:49:23.703: E/AndroidRuntime(6064): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-06 19:49:23.703: E/AndroidRuntime(6064): at java.lang.reflect.Method.invokeNative(Native Method)
01-06 19:49:23.703: E/AndroidRuntime(6064): at java.lang.reflect.Method.invoke(Method.java:511)
01-06 19:49:23.703: E/AndroidRuntime(6064): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-06 19:49:23.703: E/AndroidRuntime(6064): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-06 19:49:23.703: E/AndroidRuntime(6064): at dalvik.system.NativeStart.main(Native Method)

Categories