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

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

Related

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.

Can't display banners

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);

Writing to excel file with apache poi in android project

I have problem whit getting my project to work i will
paste the java files and error log hopefully someone can give me a hint.
The app crash when button R.id.bskickaTidSc3 in TidSc3.java is clicked.
error log
06-08 12:45:49.365: E/dalvikvm(1243): Could not find class 'org.apache.poi.hssf.usermodel.HSSFWorkbook', referenced from method com.example.spapp_beta.TidsedelExcel.SetExcelVecka
06-08 12:45:49.365: W/dalvikvm(1243): VFY: unable to resolve new-instance 67 (Lorg/apache/poi/hssf/usermodel/HSSFWorkbook;) in Lcom/example/spapp_beta/TidsedelExcel;
06-08 12:45:49.365: D/dalvikvm(1243): VFY: replacing opcode 0x22 at 0x0000
06-08 12:45:49.365: D/dalvikvm(1243): DexOpt: unable to opt direct call 0x0087 at 0x09 in Lcom/example/spapp_beta/TidsedelExcel;.SetExcelVecka
06-08 12:45:49.375: D/AndroidRuntime(1243): Shutting down VM
06-08 12:45:49.375: W/dalvikvm(1243): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-08 12:45:49.387: E/AndroidRuntime(1243): FATAL EXCEPTION: main
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidsedelExcel.SetExcelVecka(TidsedelExcel.java:17)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidSc3.onClick(TidSc3.java:96)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View.performClick(View.java:4204)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View$PerformClick.run(View.java:17355)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.handleCallback(Handler.java:725)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.dispatchMessage(Handler.java:92)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Looper.loop(Looper.java:137)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invoke(Method.java:511)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-08 12:45:49.387: E/AndroidRuntime(1243): at dalvik.system.NativeStart.main(Native Method)
06-08 12:46:37.675: E/Trace(1261): error opening trace file: No such file or directory (2)
06-08 12:46:38.065: D/gralloc_goldfish(1261): Emulator without GPU emulation detected.
TidSc3.java
package com.example.spapp_beta;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TidSc3 extends Activity implements OnClickListener {
Button skicka, visa;
TextView namn, vecka, ar, arbplts, man,tis,ons,tors,fre,lor,son,oI,oII,restid,km,trakt;
EditText v,ovrigt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tid_sc3);
ovrigt = (EditText) findViewById(R.id.eTovrigt);
v = (EditText) findViewById(R.id.eTtidSc3vecka);
namn = (TextView) findViewById(R.id.tVsamNamn);
vecka = (TextView) findViewById(R.id.tVsamVecka);
ar = (TextView) findViewById(R.id.tVsamAr);
arbplts = (TextView) findViewById(R.id.tVsamArbplts);
man = (TextView) findViewById(R.id.tVsamMan);
tis = (TextView) findViewById(R.id.tVsamTis);
ons = (TextView) findViewById(R.id.tVsamOns);
tors = (TextView) findViewById(R.id.tVsamTors);
fre = (TextView) findViewById(R.id.tVsamFre);
lor = (TextView) findViewById(R.id.tVsamLor);
son = (TextView) findViewById(R.id.tVsamSon);
oI = (TextView) findViewById(R.id.tVsamOI);
oII = (TextView) findViewById(R.id.tVsamOII);
restid = (TextView) findViewById(R.id.tVsamRestid);
km = (TextView) findViewById(R.id.tVsamKm);
trakt = (TextView) findViewById(R.id.tVsamTrakt);
visa = (Button) findViewById(R.id.bvisa);
skicka = (Button) findViewById(R.id.bskickaTidSc3);
skicka.setOnClickListener(this);
visa.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bvisa:
String s = v.getText().toString();
long l = Long.parseLong(s);
String[] veckaA = new String[16];
DbTidsedel2013 get = new DbTidsedel2013(TidSc3.this);
get.open();
veckaA = get.VeckaArray(l);
get.close();
vecka.setText(veckaA[0]);
ar.setText(veckaA[1]);
namn.setText(veckaA[2]);
arbplts.setText(veckaA[3] + "\n");
man.setText(veckaA[4]);
tis.setText(veckaA[5]);
ons.setText(veckaA[6]);
tors.setText(veckaA[7]);
fre.setText(veckaA[8]);
lor.setText(veckaA[9]);
son.setText(veckaA[10]);
restid.setText(veckaA[11]);
km.setText(veckaA[12]);
oI.setText(veckaA[13]);
oII.setText(veckaA[14]);
trakt.setText(veckaA[15]);
break;
case R.id.bskickaTidSc3:
String s1 = v.getText().toString();
long l1 = Long.parseLong(s1);
String[] veckaA1 = new String[16];
DbTidsedel2013 get1 = new DbTidsedel2013(TidSc3.this);
get1.open();
veckaA1 = get1.VeckaArray(l1);
get1.close();
TidsedelExcel tidEx = new TidsedelExcel();
try {
tidEx.SetExcelVecka(veckaA1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String ov = ovrigt.getText().toString();
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Tid vecka " + veckaA1[0]);
intent.putExtra(Intent.EXTRA_TEXT, ov);
intent.setData(Uri.parse("mailto:"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
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.tid_sc3, menu);
return true;
}
}
TidsedelExcel.java
package com.example.spapp_beta;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class TidsedelExcel {
public void SetExcelVecka (String[] vecka) throws FileNotFoundException, IOException{
Workbook workbook = new HSSFWorkbook(new FileInputStream("/assets/TsO.xls"));
Sheet sheet = workbook.getSheetAt(0);
Cell cellvecka1 = sheet.getRow(1).getCell(14);
cellvecka1.setCellValue(vecka[0]);
Cell cellvecka2 = sheet.getRow(7).getCell(0);
cellvecka2.setCellValue(vecka[0]);
Cell cellAr = sheet.getRow(1).getCell(10);
cellAr.setCellValue(vecka[1]);
Cell cellNamn = sheet.getRow(3).getCell(0);
cellNamn.setCellValue(vecka[2]);
Cell cellArbplts = sheet.getRow(3).getCell(10);
cellArbplts.setCellValue(vecka[3]);
Cell cellMan = sheet.getRow(7).getCell(3);
int man = Integer.parseInt(vecka[4]);
cellMan.setCellValue(man);
Cell cellTis = sheet.getRow(7).getCell(4);
int tis = Integer.parseInt(vecka[5]);
cellTis.setCellValue(tis);
Cell cellOns = sheet.getRow(7).getCell(5);
int ons = Integer.parseInt(vecka[6]);
cellOns.setCellValue(ons);
Cell cellTors = sheet.getRow(7).getCell(6);
int tors = Integer.parseInt(vecka[7]);
cellTors.setCellValue(tors);
Cell cellFre = sheet.getRow(7).getCell(7);
int fre = Integer.parseInt(vecka[8]);
cellFre.setCellValue(fre);
Cell cellLor = sheet.getRow(7).getCell(8);
int lor = Integer.parseInt(vecka[9]);
cellLor.setCellValue(lor);
Cell cellSon = sheet.getRow(7).getCell(9);
int son = Integer.parseInt(vecka[10]);
cellSon.setCellValue(son);
Cell cellRestid = sheet.getRow(7).getCell(10);
int restid = Integer.parseInt(vecka[11]);
cellRestid.setCellValue(restid);
Cell cellMil = sheet.getRow(7).getCell(16);
int mil = Integer.parseInt(vecka[12]);
cellMil.setCellValue(mil);
Cell cellOI = sheet.getRow(7).getCell(13);
int oI = Integer.parseInt(vecka[13]);
cellOI.setCellValue(oI);
Cell cellOII = sheet.getRow(7).getCell(14);
int oII = Integer.parseInt(vecka[14]);
cellOII.setCellValue(oII);
Cell cellTrakt = sheet.getRow(7).getCell(15);
int trakt = Integer.parseInt(vecka[15]);
cellTrakt.setCellValue(trakt);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("/assets/Tidsedel_V_" + vecka[0] + "_" + vecka[1] + ".xls");
workbook.write(fileOut);
fileOut.close();
}
}
Thanks to anyone that is kind to help out
The error says
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
Go to Project properties > Java Build Path > Order and Export tab and select the library you have used in your project..

null pointer reference android java

Hey guys i have funny little bug that i have been trying to figure now keep in mind i am student. Would like to know why it is happening ill display the class and where the error is occuring. Thankyou in advanced.
package com.example.assignment;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ViewRate extends Activity implements OnClickListener {
private int rowID;
private TextView codetv;
private TextView signtv;
private TextView ratetv;
private final String dbName="CurrencyDB";
private final String tableName="Rates";
SQLiteDatabase sampleDB=null;
//
EditText torate, fromrate;
Button convertto,convertfrom;
TextView conRate;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.viewrate);
setViews();
Bundle extra=getIntent().getExtras();
rowID=extra.getInt(MainActivity.ROW_ID);
fillViews();
convertto = (Button)findViewById(R.id.convertto);
convertfrom =(Button)findViewById(R.id.convertfrom);
convertfrom.setOnClickListener(from);
convertto.setOnClickListener(to);}
private OnClickListener to = new OnClickListener() { <-------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//converttocur();
conRate.setText("pressed"); <------testing still wont work
}
};
private OnClickListener from = new OnClickListener() { <--------ERROR
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//convertfromcur();
conRate.setText("pressed"); <--------testing
}
};
private void convertfromcur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(fromrate.getText().toString());
double com = (val / val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void converttocur() {
// TODO Auto-generated method stub
try {
double val = Double.parseDouble(ratetv.getText().toString());
double val2 = Double.parseDouble(torate.getText().toString());
double com = (val * val2);
conRate.setText("RATE:" + com);
} catch (Exception e) {
// TODO: handle exception
conRate.setText("Error");
}
}
private void fillViews() {
// TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
Cursor c = sampleDB.rawQuery("Select * from " +tableName+" where id ?", new String[] {String.valueOf(rowID)});
if(c!=null && c.moveToFirst()==true){
String code=c.getString(c.getColumnIndex("Code"));
String sign=c.getString(c.getColumnIndex("Sign"));
String rate=c.getString(c.getColumnIndex("Rate"));
codetv.setText(code);
signtv.setText(sign);
ratetv.setText(rate);
}
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open database");
}
finally{
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void setViews() {
// TODO Auto-generated method stub
codetv=(TextView)findViewById(R.id.code);
signtv=(TextView)findViewById(R.id.sign);
ratetv=(TextView)findViewById(R.id.rate);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.viewtask,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()){
case R.id.edit:
getEdit();
return true;
case R.id.delete:
getDelete();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void getDelete() {
//TODO Auto-generated method stub
try{
sampleDB=this.openOrCreateDatabase(dbName, MODE_PRIVATE,null);
sampleDB.delete(tableName, "id= "+rowID,null);
}
catch(SQLException e){
Log.e(getClass().getSimpleName(),"Could not open dB");
}
finally {
if(sampleDB!=null){
sampleDB.close();
}
}
}
private void getEdit(){
//TODO Auto-generated method stub
Intent addEdit=new Intent(this,AddEdit.class);
addEdit.putExtra("ID",rowID);
addEdit.putExtra("code",codetv.getText().toString());
addEdit.putExtra("sign",signtv.getText().toString());
addEdit.putExtra("rate",ratetv.getText().toString());
startActivity(addEdit);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And so the error is on the button clicks and i getting this error message
E/AndroidRuntime(2524): FATAL EXCEPTION: main
E/AndroidRuntime(2524): java.lang.NullPointerException
E/AndroidRuntime(2524):at .example.assignment.ViewRate.converttocur(ViewRate.java:96)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate.access$0(ViewRate.java:86)
E/AndroidRuntime(2524):at com.example.assignment.ViewRate$1.onClick(ViewRate.java:55)
E/AndroidRuntime(2524): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2524): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2524): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2524): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2524): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2524):at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2524):at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2524): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2524):at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2524): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2524): at dalvik.system.NativeStart.main(Native Method)
so here is the other logcat
E/AndroidRuntime(2743): FATAL EXCEPTION: main
E/AndroidRuntime(2743): java.lang.NullPointerException
E/AndroidRuntime(2743): at com.example.assignment.ViewRate$1.onClick(ViewRate.java:56)
E/AndroidRuntime(2743): at android.view.View.performClick(View.java:4202)
E/AndroidRuntime(2743): at android.view.View$PerformClick.run(View.java:17340)
E/AndroidRuntime(2743): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(2743): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2743): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2743): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2743): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2743): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2743): at dalvik.system.NativeStart.main(Native Method)
I have seen your code, you missed this line under onCreate method to initialize the Textview conRate so by default it initialize by null and you are referring conRate.setText("") where conRate is null thats why you are getting NullPointerException on OnClick.
conRate =(TextView)findViewById(R.id.conRate);
Hope this will help you...:)
One of these values is null:
ratetv
torate
ratetv.getText()
torate.getText()
You cannot dereference null (essentially, you cannot call methods on a null value), so you get a NullPointerException.
I think you have missed the following in your onCreate()
torate = (EditText) findViewById(R.id.to_rate)
ratetv = (TextView) findViewById(R.id.rate_tv)
Plz first check your all UI components are referenced well in your java file means in activity.
this may be the place where you get NPE.
also you are accessing intent value from other activity in onCreate() method so olz confirm that you will get value in intent or you get null value
Blockquote
just change your code::
Blockquote
you have implemented onClickListener in your activity so definetly you will get it's override method onClick so just in that method write your button click event conditionally like
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId == R.id.convertto)
{
//Here write you code when converTo button Clicked
}
else if(v.getId == R.id.converfrom)
{
//Here write your code when converfrom button clicked
}
}

App Crashes on Launch, Trying to see if file exist's for login screen

I'm creating a Class that checks to see if the file has been created (Has username and passwords.) and if it does it creates an intent to go to another class to read the data and check it againts a server via FTP. For some reason, I can't get it to work, I've tried everything and read every single web page I could, but no luck.
My Code:
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
FileOutputStream Fos;
String a;
String b;
String string = a;
String string2 = b;
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);
if (staySignedIn.isChecked()) {
String a = user.getText().toString();
String b = pass.getText().toString();
File f = new File(FILENAME);
try {
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
Fos.write(string.getBytes());
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = getBaseContext().getFileStreamPath(FILENAME);
if(file.exists());
Intent i = new Intent(LogIn.this, ChatService.class);
}
}
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("key1", p);
Intent a = new Intent(LogIn.this, logincheck.class);
a.putExtra("key", u);
a.putExtra("key1", p);
startActivity(a);
Toast.makeText(this, "Were signing you in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
LogCat:
01-19 11:37:17.601: W/dalvikvm(4411): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-19 11:37:17.621: E/AndroidRuntime(4411): FATAL EXCEPTION: main
01-19 11:37:17.621: E/AndroidRuntime(4411): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.LogIn}: java.lang.NullPointerException
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.os.Looper.loop(Looper.java:123)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-19 11:37:17.621: E/AndroidRuntime(4411): at java.lang.reflect.Method.invokeNative(Native Method)
01-19 11:37:17.621: E/AndroidRuntime(4411): at java.lang.reflect.Method.invoke(Method.java:521)
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-19 11:37:17.621: E/AndroidRuntime(4411):
at dalvik.system.NativeStart.main(Native Method)
01-19 11:37:17.621: E/AndroidRuntime(4411): Caused by: java.lang.NullPointerException
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.gta5news.bananaphone.LogIn.onCreate(LogIn.java:55)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
If line 55 is
Fos.write(string.getBytes());
then either Fos or string is uninitialized. Given that string is initialized to a which is itself uninitialized, that explains it. You need to assign a proper value to string.
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
It seems for some reason openFileOutput returning null which makes Fos null, which is throwing NullPointerException.
Add
if(Fos != null) {
Fos.write(string.getBytes());
Fos.close();
} check.
OR catch NullpointerException.

Categories

Resources