Hi i have to develop the app is insert the database from spinner in mysql database via soap webserices in android application...
i have use below webservice code:
public class Insertion {
public String insertData(String userName,String userPassword){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/androidlogin","root","");
PreparedStatement statement = con.prepareStatement("INSERT INTO user(status) VALUES ('"+userName+"');");
int result = statement.executeUpdate();
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return "Insertion successfull!!";
}
}
i have use below code for android spinner example:
public class InsertionExample extends Activity{
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://192.168.1.168:8085/XcartLogin/services/Insertion?wsdl";
private final String SOAP_ACTION = "http://xcart.com/insertData";
private final String METHOD_NAME = "insertData";
Button btninsert;
private Spinner spnMusketeers;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btninsert = (Button)findViewById(R.id.btn_insert);
btninsert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
insertValues();
}
});
}
public void insertValues(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
Spinner userName = (Spinner) findViewById(R.id.spnMusketeers);
List<String> lsMusketeers = new ArrayList<String>();
lsMusketeers.add("Q");
lsMusketeers.add("P");
lsMusketeers.add("C");
ArrayAdapter<String> aspnMusketeers =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
lsMusketeers);
aspnMusketeers.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spnMusketeers.setAdapter(aspnMusketeers);
// Set up a callback for the spinner
spnMusketeers.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) { }
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
// Code that does something when the Spinner value changes
}
});
String user_Name = userName.getContext().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("userName");//Define the variable name in the web service method
unameProp.setValue(user_Name);//Define value for fname variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
TextView result = (TextView) findViewById(R.id.textView2);
result.setText(response.toString());
}
catch(Exception e){
}
// Code that does something when the Spinner value changes
}
}
Here how is change my code for this question.
my logcat window says:
08-23 02:48:40.030: D/AndroidRuntime(4055): Shutting down VM
08-23 02:48:40.030: W/dalvikvm(4055): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
08-23 02:48:40.060: E/AndroidRuntime(4055): FATAL EXCEPTION: main
08-23 02:48:40.060: E/AndroidRuntime(4055): java.lang.NullPointerException
08-23 02:48:40.060: E/AndroidRuntime(4055): at com.android.soap.InsertionExample.insertValues(InsertionExample.java:63)
08-23 02:48:40.060: E/AndroidRuntime(4055): at com.android.soap.InsertionExample$1.onClick(InsertionExample.java:43)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.view.View.performClick(View.java:2408)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.view.View$PerformClick.run(View.java:8816)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.os.Handler.handleCallback(Handler.java:587)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.os.Handler.dispatchMessage(Handler.java:92)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.os.Looper.loop(Looper.java:123)
08-23 02:48:40.060: E/AndroidRuntime(4055): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-23 02:48:40.060: E/AndroidRuntime(4055): at java.lang.reflect.Method.invokeNative(Native Method)
08-23 02:48:40.060: E/AndroidRuntime(4055): at java.lang.reflect.Method.invoke(Method.java:521)
08-23 02:48:40.060: E/AndroidRuntime(4055): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-23 02:48:40.060: E/AndroidRuntime(4055): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-23 02:48:40.060: E/AndroidRuntime(4055): at dalvik.system.NativeStart.main(Native Method)
please help me....what error is occurred here.give me solution...
use this code for this insert function:
String selectedItem = parent.getItemAtPosition(pos).toString();
Related
When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}
I am able to compile, build, and install the project successfully And the project is running well in portrait, But In landscape mode, When I click in button, the app says: Unfortunately has stopped. Could you please help me figure this out?
This is The app Logcat In Landscape mode:
01-24 09:58:19.936: W/dalvikvm(6847): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-24 09:58:19.986: E/AndroidRuntime(6847): FATAL EXCEPTION: main
01-24 09:58:19.986: E/AndroidRuntime(6847): java.lang.NullPointerException
01-24 09:58:19.986: E/AndroidRuntime(6847): at com.Divani.Marzieh.ExamActivity.addItemList(ExamActivity.java:79)
01-24 09:58:19.986: E/AndroidRuntime(6847): at com.Divani.Marzieh.ExamActivity$1.onClick(ExamActivity.java:71)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.view.View.performClick(View.java:3511)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.view.View$PerformClick.run(View.java:14105)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.os.Handler.handleCallback(Handler.java:605)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.os.Handler.dispatchMessage(Handler.java:92)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.os.Looper.loop(Looper.java:137)
01-24 09:58:19.986: E/AndroidRuntime(6847): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-24 09:58:19.986: E/AndroidRuntime(6847): at java.lang.reflect.Method.invokeNative(Native Method)
01-24 09:58:19.986: E/AndroidRuntime(6847): at java.lang.reflect.Method.invoke(Method.java:511)
01-24 09:58:19.986: E/AndroidRuntime(6847): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-24 09:58:19.986: E/AndroidRuntime(6847): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-24 09:58:19.986: E/AndroidRuntime(6847): at dalvik.system.NativeStart.main(Native Method)
This is The examActivity Code:
public class ExamActivity extends Activity {
private EditText etInput1;
private EditText etInput2;
private Button btnAdd;
private ListView lvItem;
private ArrayList<Item> itemArrey;
private ArrayAdapter<Item> itemAdapter;
private static TabHost tabHost;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tabHost=(TabHost)findViewById(R.id.tabHost);
tabHost.setup();
TabSpec spec1=tabHost.newTabSpec("Tab 1");
spec1.setContent(R.id.tab1);
spec1.setIndicator("LIST");
TabSpec spec2=tabHost.newTabSpec("Tab 2");
spec2.setIndicator("DETAILS");
spec2.setContent(R.id.tab2);
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.setCurrentTab(id.tab1);
setUpView();
}
public static TabHost getCurrentTabHost(){
return tabHost;
}
private void setUpView() {
// TODO Auto-generated method stub
etInput1 = (EditText)this.findViewById(R.id.editText1);
etInput2 = (EditText)this.findViewById(R.id.editText2);
btnAdd = (Button)this.findViewById(R.id.button1);
lvItem = (ListView)this.findViewById(R.id.list);
itemArrey = new ArrayList<Item>();
itemArrey.clear();
itemAdapter = new CustomlistActivity(this, android.R.layout.simple_list_item_1,R.id.textView1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
if (isInputValid(etInput1) && isInputValid(etInput2)) {
if(((RadioButton)findViewById(R.id.radio0)).isChecked())
itemArrey.add(new Item(R.drawable.t,etInput1.getText().toString()+"\n"+etInput2.getText().toString()));
else if(((RadioButton)findViewById(R.id.radio1)).isChecked())
itemArrey.add(new Item(R.drawable.s,etInput1.getText().toString()+"\n"+etInput2.getText().toString()));
else if(((RadioButton)findViewById(R.id.radio2)).isChecked())
itemArrey.add(new Item(R.drawable.d,etInput1.getText().toString()+"\n"+etInput2.getText().toString()));
itemAdapter.notifyDataSetChanged();
ExamActivity.getCurrentTabHost().setCurrentTab(0);
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Please Enter Item");
return false;
} else {
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater .inflate(R.menu.mymenu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
EditText e = (EditText)findViewById(R.id.editText3);
switch (item.getItemId()) {
case R.id.item1:
Toast toast = Toast.makeText(ExamActivity.this, e.getText().toString(), 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
whenever you change the orientation of the screen the activity gets restarted after that the onStart() method is called.
Initialize your code that you are using at ExamActivity.addItemList(ExamActivity.java:79) in your onStart() method ex: your list or array
go through the site http://www.vogella.com/tutorials/AndroidLifeCycle/article.html#configurationchange
Do you have a separate layout main.xml for landscape, ie layout/main.xml and layout-land/main.xml ? If so then check that layout-land/main.xml is not missing some or all of the radio buttons radio0/1/2.
I'm having implement android demo for application pin using shared preferences which i enter pin and confirm the pin.The problem is that when I am accessing this values, it is not returning updated values, it gives me NullPointerException.
String strGetPin;
public final String pref_filename = "settings";
String myPassword;
static SharedPreferences shaedPref;
public static String strdataReturned = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_list);
activity = this;
edtxt_EnterPin = (EditText) findViewById(R.id.edtxt_Pin);
edtxt_NewPin = (EditText) findViewById(R.id.edtxt_NewPin);
edtxt_ConfirmPin = (EditText) findViewById(R.id.edtxt_ConfirmPin);
shaedPref = getSharedPreferences(pref_filename, 0);
strdataReturned = shaedPref.getString("user", "");
if (strdataReturned.equals("")) {
SharedPreferences.Editor editor = shaedPref.edit();
editor.putString("user", "1234"); // newData is new pass,passwordKey is key
editor.commit();
}
btnChangePin = (Button) findViewById(R.id.btn_ChangePin);
btnChangePin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myDialog = new Dialog(Settings_Activity.this);
myDialog.setContentView(R.layout.pin_change);
myDialog.setTitle("Application PIN Change");
myDialog.setCancelable(false);
//Button For Change Pin save
Button btnChange = (Button) myDialog.findViewById(R.id.btn_Save);
btnChange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String stringData = edtxt_EnterPin.getText().toString().trim();
strdataReturned = shaedPref.getString("user", ""); // key/def message
// if stored password is equal to entered password
if (strdataReturned.equals(stringData)) {
String newData = edtxt_NewPin.getText().toString().trim();
SharedPreferences.Editor editor = shaedPref.edit();
editor.putString("user", newData); // newData is new pass, passwordKey is key
editor.commit();
Toast.makeText(getApplicationContext(), "PIN Change successfully", Toast.LENGTH_LONG).show();
edtxt_EnterPin.setText("");
edtxt_NewPin.setText("");
} else {
Toast.makeText(getApplicationContext(), "Wrong Pin!", Toast.LENGTH_LONG).show();
edtxt_EnterPin.setText("");
edtxt_NewPin.setText("");
}
}
});
Button btnCancel = (Button) myDialog.findViewById(R.id.btn_Cancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myDialog.dismiss();
}
});
myDialog.show();
}
});
}
Logcat:
04-09 18:42:12.694: D/(29235): onClick: Stoping Service
04-09 18:42:12.781: E/(29235): Service Stopped
04-09 18:42:19.861: D/dalvikvm(29235): GREF has increased to 201
04-09 18:42:50.712: D/AndroidRuntime(29235): Shutting down VM
04-09 18:42:50.712: W/dalvikvm(29235): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-09 18:42:50.721: E/AndroidRuntime(29235): FATAL EXCEPTION: main
04-09 18:42:50.721: E/AndroidRuntime(29235): java.lang.NullPointerException
04-09 18:42:50.721: E/AndroidRuntime(29235): at com.sms_alert.Settings_Activity$1$1.onClick(Settings_Activity.java:95)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.view.View.performClick(View.java:2485)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.view.View$PerformClick.run(View.java:9080)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.os.Handler.handleCallback(Handler.java:587)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.os.Handler.dispatchMessage(Handler.java:92)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.os.Looper.loop(Looper.java:123)
04-09 18:42:50.721: E/AndroidRuntime(29235): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-09 18:42:50.721: E/AndroidRuntime(29235): at java.lang.reflect.Method.invokeNative(Native Method)
04-09 18:42:50.721: E/AndroidRuntime(29235): at java.lang.reflect.Method.invoke(Method.java:507)
04-09 18:42:50.721: E/AndroidRuntime(29235): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-09 18:42:50.721: E/AndroidRuntime(29235): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-09 18:42:50.721: E/AndroidRuntime(29235): at dalvik.system.NativeStart.main(Native Method)
04-09 18:42:53.932: I/Process(29235): Sending signal. PID: 29235 SIG: 9
Try clearing the SharedPreferences before writing to it.
editor.clear();
I'm trying to develop a very simple apk.
I'm using a textView to show two team's name that i enter in a previous activity (brought here with the intent that open this activity).
When i try to use setText to show the names of these teams the apk crash.
This is the class that crash:
public class MatchPage extends Activity {
private String locali= null;
private String ospiti= null;
private TextView localiTV;
private TextView ospitiTV;
private MatchRugby partita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
localiTV =(TextView) findViewById(R.id.localiTV);
ospitiTV =(TextView) findViewById(R.id.ospitiTV);
getLocali();
getOspiti();
createMatch();
localiTV.setText("Locali /n"+ partita.teamA.getName());
ospitiTV.setText("Ospiti /n"+ partita.teamB.getName());
}
/**
* Prende il nome della squadra locale dall'intent
* #return
*/
public String getLocali(){
Intent matchStart = getIntent();
String locali = matchStart.getStringExtra(NewMatchPage.LOCALI);
return locali;
}
/**
* prende il nome della squadra ospite dall'intent
* #return
*/
public String getOspiti(){
Intent matchStart = getIntent();
String ospiti = matchStart.getStringExtra(NewMatchPage.OSPITI);
return ospiti;
}
public MatchRugby createMatch(){
TeamRugby teamLocali= new TeamRugby(locali);
TeamRugby teamOspiti= new TeamRugby(ospiti);
MatchRugby partita= new MatchRugby(teamLocali, teamOspiti);
return partita;
}
}
This is the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/localiTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/ospitiTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
This is the class that send the intent:
public class NewMatchPage extends Activity {
public static final String LOCALI = null;
public static final String OSPITI = null;
private Button startMatch;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_match);
startMatch= (Button) findViewById(R.id.startMatch);
startMatch.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
startMatch();
}
});
}
public void startMatch(){
Intent startMatch= new Intent(this, MatchPage.class);
//Prendo il testo scritto nella casella locali e la porto nella partita
EditText locali= (EditText) findViewById(R.id.Locali);
String locali1 = locali.getText().toString();
startMatch.putExtra(LOCALI, locali1);
//Prendo il testo scritto nella casella ospiti e la porto nella partita
EditText ospiti= (EditText) findViewById(R.id.Ospiti);
String ospiti1 = ospiti.getText().toString();
startMatch.putExtra(OSPITI, ospiti1);
//inizio la partita
startActivity(startMatch);
}
}
And finally that's the logcat log:
04-24 16:49:08.928: W/dalvikvm(1377): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
04-24 16:49:08.958: E/AndroidRuntime(1377): FATAL EXCEPTION: main
04-24 16:49:08.958: E/AndroidRuntime(1377): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gmail.david.corsalini.sportscout/com.gmail.david.corsalini.sportscout.MatchPage}: java.lang.NullPointerException
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.access$600(ActivityThread.java:123)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.os.Looper.loop(Looper.java:137)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.main(ActivityThread.java:4424)
04-24 16:49:08.958: E/AndroidRuntime(1377): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 16:49:08.958: E/AndroidRuntime(1377): at java.lang.reflect.Method.invoke(Method.java:511)
04-24 16:49:08.958: E/AndroidRuntime(1377): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-24 16:49:08.958: E/AndroidRuntime(1377): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-24 16:49:08.958: E/AndroidRuntime(1377): at dalvik.system.NativeStart.main(Native Method)
04-24 16:49:08.958: E/AndroidRuntime(1377): Caused by: java.lang.NullPointerException
04-24 16:49:08.958: E/AndroidRuntime(1377): at com.gmail.david.corsalini.sportscout.MatchPage.onCreate(MatchPage.java:25)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.Activity.performCreate(Activity.java:4465)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-24 16:49:08.958: E/AndroidRuntime(1377): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
04-24 16:49:08.958: E/AndroidRuntime(1377): ... 11 more
MatchRugby class
public class MatchRugby {
public TeamRugby teamA;
public TeamRugby teamB;
/**
* Costruttore della partita
*/
public MatchRugby(TeamRugby teamA, TeamRugby teamB){
this.teamA=teamA;
this.teamB=teamB;
}
/**
* #return the teamA
*/
public TeamRugby getTeamA() {
return teamA;
}
/**
* #param teamA the teamA to set
*/
public void setTeamA(TeamRugby teamA) {
this.teamA = teamA;
}
/**
* #return the teamB
*/
public TeamRugby getTeamB() {
return teamB;
}
/**
* #param teamB the teamB to set
*/
public void setTeamB(TeamRugby teamB) {
this.teamB = teamB;
}
public void EndOfMatch(){
//nothing to do with the problem
}
}
Your variable scoping is all off. set up your class like this:
public class MatchPage extends Activity {
private String locali= null;
private String ospiti= null;
private TextView localiTV;
private TextView ospitiTV;
private MatchRugby partita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.match);
localiTV =(TextView) findViewById(R.id.localiTV);
ospitiTV =(TextView) findViewById(R.id.ospitiTV);
getLocali();
getOspiti();
createMatch();
localiTV.setText("Locali /n"+ partita.teamA.getName());
ospitiTV.setText("Ospiti /n"+ partita.teamB.getName());
}
/**
* Prende il nome della squadra locale dall'intent
* #return
*/
public String getLocali(){
if (locali == null) {
Intent matchStart = getIntent();
locali = matchStart.getStringExtra(NewMatchPage.LOCALI);
}
return locali;
}
/**
* prende il nome della squadra ospite dall'intent
* #return
*/
public String getOspiti(){
if (ospiti == null) {
Intent matchStart = getIntent();
ospiti = matchStart.getStringExtra(NewMatchPage.OSPITI);
}
return ospiti;
}
public MatchRugby createMatch(){
TeamRugby teamLocali= new TeamRugby(locali);
TeamRugby teamOspiti= new TeamRugby(ospiti);
partita = new MatchRugby(teamLocali, teamOspiti);
return partita
}
private String locali
private String ospiti
private MatchRugby partita
}
You have a NullPointerException at line #25 of your MatchPage class in onCreate method. Not sure which line exactly it is in the code you posted, but my best guess is your findViewById call fails to find anything.
java.lang.NullPointerException
at com.gmail.david.corsalini.sportscout.MatchPage.onCreate(MatchPage.java:25)
Seem that you partita object is null from the above error. And from your code where you are initializing it
createMatch();
replace the above method with below line
partita = createMatch();
Also you can change the following code::
public void createMatch(){
TeamRugby teamLocali= new TeamRugby(locali);
TeamRugby teamOspiti= new TeamRugby(ospiti);
partita= new MatchRugby(teamLocali, teamOspiti);
}
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.