Can't display banners - java

I have this activity - including the needed code in order to load the admob banner ads.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.gs.britishjokes.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AllJokes extends Activity {
public static ArrayAdapter<String> adapter;
public static ListView listView;
private AdView adView;
/* Your ad unit id. Replace with your actual ad unit id. */
private static final String AD_UNIT_ID = "ca-app-pub-codehere/code";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_jokes);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
// .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
.build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
final GlobalsHolder globals = (GlobalsHolder)getApplication();
// if(globals.isLoaded == false){ SETJOKESNAMELIST MAI SE POLZVA OT DRUGO ACTIVITY!!!! ZATOVA IZLIZA PRAZNO SLED PROVERKATA!
new loadJson().execute();
// }
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
adapter.clear();
adapter.addAll(globals.getMyStringArray());
listView = (ListView) findViewById(R.id.allJokesList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
globals.setClickedJokeName((String) ((TextView) view).getText());
openJokeBody(view);
globals.setClickedPosition(position);
// When clicked, shows a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.all_jokes, menu);
return true;
}
public class loadJson extends AsyncTask<Void, Integer, String[]>{
private ProgressDialog Dialog = new ProgressDialog(AllJokes.this);
#Override
protected void onPreExecute()
{
Dialog.setMessage("Fetching the latest jokes!");
Dialog.show();
}
#Override
protected String[] doInBackground(Void... params) {
/*Getting the joke names JSON string response from the server*/
URL u;
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
try {
u = new URL("https://site.com/android/Jokes/showJokes.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
try {
u = new URL("https://site.com/android/Jokes/showJokesBody.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer2.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
// return buffer.toString(); ako se naloji da vurna - da pogledna tva return4e
return new String[]{buffer.toString(), buffer2.toString()};
}
#SuppressLint("NewApi")
protected void onPostExecute(String[] buffer) {
final GlobalsHolder globals = (GlobalsHolder)getApplication();
JSONArray jsonArray = new JSONArray();
JSONArray jsonArray1 = new JSONArray();
try {
jsonArray = new JSONArray(buffer[0]);
jsonArray1 = new JSONArray(buffer[1]);
} catch (JSONException e) {
e.printStackTrace();
}
/*Looping trough the results and adding them to a list*/
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list1 = new ArrayList<String>();
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
try {
list.add(jsonArray.get(i).toString());
globals.setJokeNamesList(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if (jsonArray != null) {
int len = jsonArray1.length();
for (int i=0;i<len;i++){
try {
list1.add(jsonArray1.get(i).toString());
globals.setList(list1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/* Redrwawing the view */
adapter.clear();
adapter.addAll(list);
Dialog.dismiss();
globals.setLoaded(true);
}
}
/*This method opens the new activity - TopJokesBody when a joke name from the list is clicked*/
public void openJokeBody(View view) {
Intent intent = new Intent(this, AllJokesBody.class);
startActivity(intent);
}
}
It is my 1st try and I already stucked. Logcat is throwing tons of exceptions and to be honest I can't understand what I'm doing wrong.
Here the exceptions are:
03-29 13:55:37.713: E/AndroidRuntime(1750): FATAL EXCEPTION: main
03-29 13:55:37.713: E/AndroidRuntime(1750): Process: com.gs.britishjokes, PID: 1750
03-29 13:55:37.713: E/AndroidRuntime(1750): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gs.britishjokes/com.gelasoft.britishjokes.AllJokes}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Handler.dispatchMessage(Handler.java:102)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Looper.loop(Looper.java:136)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invokeNative(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invoke(Method.java:515)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-29 13:55:37.713: E/AndroidRuntime(1750): at dalvik.system.NativeStart.main(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.widget.AdapterView.addView(AdapterView.java:452)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.gelasoft.britishjokes.AllJokes.onCreate(AllJokes.java:55)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Activity.performCreate(Activity.java:5231)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-29 13:55:37.713: E/AndroidRuntime(1750): ... 11 more
I'm sure that I miss something inside of the xml layout file, but I'm not able to spot it as a total beginner.
Ps. here the layout is:
<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=".AllJokes" >
<ListView
android:id="#+id/allJokesList"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</RelativeLayout>
Should I declare something in it? Please, give me a clue!

Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
you cant add a view to adapterview

your issue is with
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
You need to add the adView inside the adapter
http://googleadsdeveloper.blogspot.co.il/2012/03/embedding-admob-ads-within-listview-on.html

Don't try to add an AdView as an element in a ListView. It is a recipe for pain as it will be entirely different to your other items with different needs.
Add it as it's own element either above or below your ListView.
Instead create a LinearLayout either above or below your ListView
<LinearLayout android:id="#+id/adViewContainer
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
and then change this part of your onCreate to
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
final ViewGroup adViewContainer = (ViewGroup) findViewById(R.id.adViewContainer);
adViewContainer.addView(adView);

Related

Android display SD card files throws java.lang.NullPointerException

This is the MainActivity file. When I run it in the emulator and phone, logcat displays a crash due to a NullPointerException. I've read a lot about not letting the user or another activity pass "null" value to my method but could not get around this.
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I used a listview with id= "filelist" in layout
ListView lv;
ArrayList<String> FilesInFolder;
FilesInFolder = GetFiles(Environment.getExternalStorageDirectory().getPath()+ "/sdcard/");
lv = (ListView)findViewById(R.id.filelist);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
}
This is the logcat:
07-02 01:09:40.500 4407-4407/com.amenhotep.filelister W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
07-02 01:09:40.501 4407-4407/com.amenhotep.filelister E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amenhotep.filelister, PID: 4407
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amenhotep.filelister/com.amenhotep.filelister.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.amenhotep.filelister.MainActivity.GetFiles(MainActivity.java:44)
at com.amenhotep.filelister.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
the problem is in your sdcard path, use this code to get path of sdcard
String DIR_SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
and there is no need to add "/sdcard/" to it, also change your GetFiles method, and remove mkdirs() because sdcard exists before.
look at this example
File sdcard_files_and_folders[] = new File(DIR_SDCARD).listFiles();
for (File fileOrFolder: sdcard_files_and_folders) {
// do any thing that you want, add them to list or...
Log.i("FILE", fileOrFolder.toString());
}

How to fix application has stopped in android app when clicking another button inside main activity?

I have an app that when logged in by user the user redirects to main activity which had his personal details displayed and had two buttons to click: dashboard button redirected to his dashboard manager settings and a button log out. When logged in all is working fine showing his personal details and when I clicked dashboard button for his dashboard settings the app is unfortunately stopped. It said errors in my log cat which I can't fix with my own. I am new to Android. I searched and tried threads here in SO that has same problems with me but still can not be solved. Anybody with a great heart can help me to solve this? It's been quiet a week I'm stuck on this.
note* my dashboard button is calling another layout that contains two buttons
This is my main activity java :
package com.myapp;
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.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 org.json.JSONArray;
import org.json.JSONObject;
import library.JSONParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
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.TextView;
public class ProfileView extends Activity implements OnClickListener{
private Button bLogout, backdashboard;
private TextView tvusername, tvfullname;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONArray user;
JSONObject display;
//String name for my sharedpref extras
String ngalan;
// Profile JSON url
private static final String PROFILE_URL = "http://10.0.2.2/webservice/profile.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
//setup textview
tvusername=(TextView)(findViewById(R.id.tvusernamedisplay));
tvfullname=(TextView)(findViewById(R.id.tvfullname));
//settup buttons
backdashboard=(Button)(findViewById(R.id.backdashboard));
bLogout=(Button)(findViewById(R.id.blogout));
//button listener
backdashboard.setOnClickListener(this);
bLogout.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras.containsKey("username")) {
ngalan = extras.getString("username");
// Loading Profile in Background Thread
new LoadProfile().execute();
}
}
#Override
public void onClick(View args) {
// TODO Auto-generated method stub
switch (args.getId()) {
case R.id.backdashboard:
Intent r = new Intent(this, Dashboard.class);
startActivity(r);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(ProfileView.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
class LoadProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileView.this);
pDialog.setMessage("Loading Profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", ngalan));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
// dismiss the dialog after getting all products
pDialog.dismiss();
try
{
display = new JSONObject(json);
JSONArray user = display.getJSONArray("user");
JSONObject jb= user.getJSONObject(0);
String idnum = jb.getString("username");
String fulname = jb.getString("lastname");
// displaying all data in textview
tvusername.setText(idnum );
tvfullname.setText(fulname);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
This is my Dashboard activity java another activity calls when dashboard button is clicked...
package com.myapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Dashboard extends Activity implements OnClickListener{
private Button view, manage, logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
initialise();
}
private void initialise() {
// TODO Auto-generated method stub
//settup buttons
manage=(Button)(findViewById(R.id.bManage));
view=(Button)(findViewById(R.id.bView));
logout=(Button)(findViewById(R.id.blogout));
//button listener
manage.setOnClickListener(this);
view.setOnClickListener(this);
logout.setOnClickListener(this);
}
#Override
public void onClick(View item) {
// TODO Auto-generated method stub
switch (item.getId()) {
case R.id.bManage:
Intent r = new Intent(this, Manage.class);
startActivity(r);
finish();
break;
case R.id.bView:
Intent l = new Intent(this, View.class);
startActivity(l);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(Dashboard.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
}
This is my log cat error message"
08-23 18:59:36.949: E/AndroidRuntime(900): FATAL EXCEPTION: main
08-23 18:59:36.949: E/AndroidRuntime(900): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
Please help me guys :(
This is the full logcat message:
Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Looper.loop(Looper.java:137)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.main(ActivityThread.java:5039)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invokeNative(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invoke(Method.java:511)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-23 18:59:36.949: E/AndroidRuntime(900): at dalvik.system.NativeStart.main(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): Caused by: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at com.myapp.Dashboard.onCreate(Dashboard.java:27)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Activity.performCreate(Activity.java:5104)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-23 18:59:36.949: E/AndroidRuntime(900): ... 11 more
I guess that NPE occurs in this line: grade.setOnClickListener(this);
You don't initialize this variable anywhere.

Navigation drawer combined with google maps crashes

I tried to launch the navigation drawer with google maps, but from some reason it crashes me. (It doesn't even load the first map).
I think the problem is about the adapter or about the xml's files.
The LogCat says that the problem is at line 102 :
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
But I can't find what's wrong it this line.
I Attaching the xml fils, the Java and the LogCat.
I followed excatly as it mentioned in the offical Android Developer site... but I still don't get what's wrong in my code.
I suspect it's about one of the XML. maybe the Fragment FrameLayout need to change with the FrameLayout of the map that in the drawerlayout.xml ?
I'm a little confused. what can be the soulution to make the application run without crashing?(it crashes run away, and doesn't load the map)
Thank you.
drawer_layout.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
MainActivity.Java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends Activity implements LocationListener {
// maps&location global variables
GoogleMap map;
public double longitude;
public double latitude;
Location location;
// navigation drawer global variables
private String[] mNavigationTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
map.setMyLocationEnabled(true);
// get location code
final Criteria criteria = new Criteria();
final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.getBestProvider(criteria, true);
final Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// animates the camera in zoom 7 to the location of the user
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng UserLoc = new LatLng(latitude, longitude);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(UserLoc, 7));
}
// else {
// Toast.makeText(getApplicationContext(), "cant get loc",
// Toast.LENGTH_LONG).show();
// }
// LocationButtonListener
map.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
// if the Gps is off it openes a dialog to turn it off
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else /* if (location == null) */{
// if it on, animates to the current position
final Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location
.getLongitude()), 15));
return false;
}
return false;
}
});
// navigation drawer declarations&adapter
mNavigationTitles = getResources().getStringArray(
R.array.Navigation_Drawer);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_layout, mNavigationTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
selectItem(position);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.firstlogo, R.string.Yes, R.string.no) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// end of OnCreate function
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private void selectItem(int position) {
// Create a new fragment and specify the planet to show based on
// position
switch (position) {
case 1:
Toast.makeText(getApplicationContext(), "cant get loc",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mNavigationTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
setUpMapIfNeeded();
super.onResume();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (map == null) {
map = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (map != null) {
}
}
}
// function that opened an activity to turn on the GPS
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS is off ")
.setCancelable(true)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int id) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog,
final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
LogCat:
06-05 12:15:53.816: E/AndroidRuntime(22316): FATAL EXCEPTION: main
06-05 12:15:53.816: E/AndroidRuntime(22316): java.lang.RuntimeException: Unable to start activity ComponentInfo{nir.rauch.flantir/nir.rauch.flantir.MainActivity}: java.lang.NullPointerException
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.access$700(ActivityThread.java:159)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.os.Handler.dispatchMessage(Handler.java:99)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.os.Looper.loop(Looper.java:137)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.main(ActivityThread.java:5419)
06-05 12:15:53.816: E/AndroidRuntime(22316): at java.lang.reflect.Method.invokeNative(Native Method)
06-05 12:15:53.816: E/AndroidRuntime(22316): at java.lang.reflect.Method.invoke(Method.java:525)
06-05 12:15:53.816: E/AndroidRuntime(22316): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
06-05 12:15:53.816: E/AndroidRuntime(22316): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
06-05 12:15:53.816: E/AndroidRuntime(22316): at dalvik.system.NativeStart.main(Native Method)
06-05 12:15:53.816: E/AndroidRuntime(22316): Caused by: java.lang.NullPointerException
06-05 12:15:53.816: E/AndroidRuntime(22316): at nir.rauch.flantir.MainActivity.onCreate(MainActivity.java:102)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.Activity.performCreate(Activity.java:5372)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
06-05 12:15:53.816: E/AndroidRuntime(22316): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
06-05 12:15:53.816: E/AndroidRuntime(22316): ... 11 more
your actual problem is on below line
replace
setContentView(R.layout.activity_main);
with
setContentView(R.layout.drawer_layout);
you bind wrong xml and you do not load fragment and drawer on same acivity
also comment all map code in on create and put it on your new fragment class... and load map on fragment class not in activity class.

nullpointerexception cannot start activity

I keep getting nullpointerexception errors when I try to start a second activity from my main activity, my main activity code goes as such:
package com.cep.daredevil;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public boolean filled = true;
EditText taskArray[] = new EditText[200];
EditText descArray[] = new EditText[200];
String taskArr[] = new String[200];
String descArr[] = new String[200];
int taskId[] = new int[200];
int descId[] = new int[200];
int n=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout llayout = (LinearLayout)findViewById(R.id.llayout);
Button addfield = new Button(this);
addfield.setText("+");
llayout.addView(addfield);
addfield.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
addtask();
}
});
for(int i=0;i<3;i++)
{
addtask();
}
LinearLayout blayout = (LinearLayout)findViewById(R.id.blayout);
Button submit = new Button(this);
submit.setText("Enter Dare");
Button viewdare = new Button(this);
viewdare.setText("View Dares");
blayout.addView(submit);
blayout.addView(viewdare);
submit.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
inputdare(null);
}
});
viewdare.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
listdare();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void addtask()
{
LinearLayout llayout = (LinearLayout)findViewById(R.id.llayout);
taskArray[n] = new EditText(this);
taskArray[n].setHint("Task Title");
taskArray[n].setId(n+10000000);
taskArray[n].setPadding(26,30,25,8);
descArray[n] = new EditText(this);
descArray[n].setHint("Task Description");
descArray[n].setId(n+20000000);
llayout.addView(taskArray[n]);
llayout.addView(descArray[n]);
n++;
}
public void inputdare(View v){
EditText daretitle = (EditText)findViewById(R.id.title);
String dare = daretitle.getText().toString();
for (int i=0;i<n;i++)
{
if (taskArr[i] != null)
{
taskArr[i] = taskArray[i].getText().toString();
}
Integer id = taskArray[i].getId();
if (id != null)
{
taskId[i] = id;
}
}
Intent intent = new Intent(this, DisplayDares.class);
Bundle bundle = new Bundle();
bundle.putStringArray("TASKS", taskArr);
bundle.putIntArray("TASKID", taskId);
bundle.putBoolean("INPUT", true);
intent.putExtras(bundle);
startActivity(intent);
}
}
public void listdare()
{
Intent intent = new Intent(this, DisplayDares.class);
Bundle bundle = new Bundle();
bundle.putBoolean("INPUT", false);
intent.putExtras(bundle);
startActivity(intent);
}
}
the function that seems to be causing the problem is in my second activity, over here:
package com.cep.daredevil;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DisplayDares extends Activity {
public final static String PREFS = "Preferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_dare);
setupActionBar();
Bundle bundle = getIntent().getExtras();
Boolean input = bundle.getBoolean("INPUT");
if (input == false){}
else
{
int[] taskId = bundle.getIntArray("TASKID");
final String[] taskArray = bundle.getStringArray("TASKS");
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
TextView test = (TextView)findViewById(taskId[0]);
test.setText(taskArray[1]);
layout.addView(test);
}
}
}
the error I get is this:
03-08 13:32:18.053: E/AndroidRuntime(6873): FATAL EXCEPTION: main
03-08 13:32:18.053: E/AndroidRuntime(6873): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cep.daredevil/com.cep.daredevil.DisplayDares}: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.os.Looper.loop(Looper.java:137)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-08 13:32:18.053: E/AndroidRuntime(6873): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 13:32:18.053: E/AndroidRuntime(6873): at java.lang.reflect.Method.invoke(Method.java:511)
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-08 13:32:18.053: E/AndroidRuntime(6873): at dalvik.system.NativeStart.main(Native Method)
03-08 13:32:18.053: E/AndroidRuntime(6873): Caused by: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.cep.daredevil.DisplayDares.onCreate(DisplayDares.java:32)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.Activity.performCreate(Activity.java:5104)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
After pasing your code it seems line 34 is:
layout.addView(test);
So this line generates a nullpointer exception
Check if the id of your layout is the same.
Tip:
Further in your error stacktrace you can see what causes the error:
03-08 13:32:18.053: E/AndroidRuntime(6873): Caused by: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.cep.daredevil.DisplayDares.onCreate(DisplayDares.java:34)
DisplayDares.java:34
Means line 34 in your DisplayDares.java file.
You will see it is the following line:
layout.addView(test);
Now test cannot be NULL because it wouldn't have thrown that error. So layout must be.

App Crashes when Button is clicked (Passing a string between two classes.)

I've started on another class that get's two strings from another class, I've only set up one so far, but I just tested it out, but when I fill in my two edit text's and hit submit it crashes.
First Class (Launcher Class)
package com.gta5news.bananaphone;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
FileOutputStream Fos;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
try {
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (staySignedIn.isChecked()) {
String a = user.getText().toString();
String b = pass.getText().toString();
File f = new File(FILENAME);
try {
Fos = new FileOutputStream(f);
//Write some Data
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (pass.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else if (user.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key", p);
Intent a = new Intent(LogIn.this, logincheck.class);
startActivity(a);
Toast.makeText(this, "Were signing you in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
Second Class:
package com.gta5news.bananaphone;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class logincheck extends Activity {
String GotBread;
TextView user;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.logincheck);
user = (TextView) findViewById(R.layout.logincheck);
SetUp();
}
public void SetUp() {
// TODO Auto-generated method stub
Bundle GotData = getIntent().getExtras();
GotBread = GotData.getString("key");
user.setText(GotBread); {
}
}
}
LogCat:
01-19 08:53:56.641: E/AndroidRuntime(3319): ... 11 more
01-19 08:56:28.561: E/AndroidRuntime(3384): FATAL EXCEPTION: main
01-19 08:56:28.561: E/AndroidRuntime(3384): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.logincheck}: java.lang.NullPointerException
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.os.Looper.loop(Looper.java:123)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-19 08:56:28.561: E/AndroidRuntime(3384): at java.lang.reflect.Method.invokeNative(Native Method)
01-19 08:56:28.561: E/AndroidRuntime(3384): at java.lang.reflect.Method.invoke(Method.java:521)
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-19 08:56:28.561: E/AndroidRuntime(3384): at dalvik.system.NativeStart.main(Native Method)
01-19 08:56:28.561: E/AndroidRuntime(3384): Caused by: java.lang.NullPointerException
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.gta5news.bananaphone.logincheck.SetUp(logincheck.java:24)
01-19 08:56:28.561: E/AndroidRuntime(3384): at com.gta5news.bananaphone.logincheck.onCreate(logincheck.java:17)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-19 08:56:28.561: E/AndroidRuntime(3384): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-19 08:56:28.561: E/AndroidRuntime(3384): ... 11 more
Get Bundle in Oncreate Method
And
Use Like
Intent i = new Intent(Login.this,logincheck.class);
i.putExtra("key", user);
i.putExtra("key1", pass);
startActivity(i);
And
user = (TextView) findViewById(R.layout.logincheck);
Instead of
user = (TextView) findViewById(R.id.logincheck);
So User is Null
On your main activity you're creating the Bundle and inserting the content in it, but you're not sending it to the the intent.
You should put the information on the Intent before starting the second activity. Do something like this:
Intent a = new Intent(LogIn.this, logincheck.class);
a.putExtra("key", u);
a.putExtra("key", p);
startActivity(a);
I will try to give u a clue how to solve it..it can be even more fail-proffed but this should work for u..
Intent i = new Intent(LogIn.this, logincheck.class);
i.putExtra("username", sUsername);
i.putExtra("password", SPassword);
To get the saved data in new activity try with:
String newString;
if(extras == null) {
sUsernameInNewActivity = null;
sPasswordInNewActivity = null;
} else {
sUsernameInNewActivity = extras.getString("username");
sPasswordInNewActivity = extras.getString("password");
}
btw. A lot of bad practice in your code.. :( I have troubles to read it easy..
for example:
you have two variables with different scope and type but exactly the same name (try to find it)
did u want to join something with this code or???
send.putString("key", u);
send.putString("key", p);
how u thought to get them later? together/separately?
Hope u will solve it. Cheers

Categories

Resources