I'm working with a listview which on click opens a dialog box which contains an edittext and a button. On button click, the value entered in the editText is saved in a textView from listview item which had been pressed before. The problem is that the value wasn't saved anymore if I reopened the application. I tried to make it save using sharedPrefences but it's crashing and shows 3 nullpointerexception and can't deal with them.
Here is my:
Carnet.java
package com.cngcnasaud.orar;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
#SuppressWarnings("deprecation")
public class Carnet extends TabActivity {
// TabSpec Names
private static final String NOTA_SPEC = "Note";
private static final String ABSENTE_SPEC = "Absente";
private static final String MEDII_SPEC = "Medii";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carnet);
TabHost tabHost = getTabHost();
TabSpec NotaSpec = tabHost.newTabSpec(NOTA_SPEC);
// Tab Icon
NotaSpec.setIndicator(NOTA_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent notaIntent = new Intent(this, Note.class);
// Tab Content
NotaSpec.setContent(notaIntent);
TabSpec AbsenteSpec = tabHost.newTabSpec(ABSENTE_SPEC);
AbsenteSpec.setIndicator(ABSENTE_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent absenteIntent = new Intent(this, Absente.class);
AbsenteSpec.setContent(absenteIntent);
TabSpec MediiSpec = tabHost.newTabSpec(MEDII_SPEC);
AbsenteSpec.setIndicator(MEDII_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent mediiIntent = new Intent(this, MediiL.class);
AbsenteSpec.setContent(mediiIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(NotaSpec);
tabHost.addTab(AbsenteSpec);
tabHost.addTab(MediiSpec);
}
}
Note.java
package com.cngcnasaud.orar;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Note extends Activity {
private static final ListAdapter NoteAdapter = null;
ListView lv;
Context context;
ArrayList<?> prgmName;
TextView text;
public static String[] prgmNameList = { "Romana - ", "Matematica - ",
"Lb. Engleza - ", "Lb. Germana/Franceza - ", "Istorie - ",
"Geografie - ", "Biologie - ", "Fizica - ", "Ed. Fizica - " };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_listview);
text = (TextView) findViewById(R.id.textView2);
context = this;
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
}
#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 onStop() {
// TODO Auto-generated method stub
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
// Variable is public for clarity.
String toSave = EncodeDecode.encode(adapter.savedEntries);
SharedPreferences.Editor editor = getSharedPreferences("LV Data",
MODE_PRIVATE).edit();
editor.putString("TVEntries", toSave);
editor.commit();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
SharedPreferences prefs = getSharedPreferences("LV Data", MODE_PRIVATE);
String encoded = prefs.getString("TVEntries", "");
String[] entries;
if (encoded.equals(""))
entries = null;
else
entries = EncodeDecode.decode(encoded);
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
adapter.savedEntries = entries;
lv.setAdapter(adapter);
super.onResume();
}
}
And NoteAdapter.java:
package com.cngcnasaud.orar;
import java.util.Arrays;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class NoteAdapter extends BaseAdapter {
String[] result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
private Dialog dialog;
String[] savedEntries;
String[] saved = null;
public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
// TODO Auto-generated constructor stub
result = prgmNameList;
context = note;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (saved == null) {
savedEntries = new String[result.length];
Arrays.fill(savedEntries, "");
} else
savedEntries = saved;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return savedEntries[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
public TextView text;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.note_items, null);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.text = (TextView) rowView.findViewById(R.id.textView2);
holder.text.setText(savedEntries[position]);
holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Materie:" + result[position]);
final EditText txtMode = (EditText) dialog
.findViewById(R.id.dialog);
Button btnSave = (Button) dialog.findViewById(R.id.bsave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = txtMode.getText().toString();
holder.text.setText(data);
savedEntries[position] = data;
dialog.dismiss();
Log.d("data", data);
}
});
dialog.show();
}
});
return rowView;
}
}
logcat:
04-18 19:27:28.558: E/AndroidRuntime(1419): FATAL EXCEPTION: main
04-18 19:27:28.558: E/AndroidRuntime(1419): Process: com.cngcnasaud.orar, PID: 1419
04-18 19:27:28.558: E/AndroidRuntime(1419): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Carnet}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.os.Handler.dispatchMessage(Handler.java:102)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.os.Looper.loop(Looper.java:136)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-18 19:27:28.558: E/AndroidRuntime(1419): at java.lang.reflect.Method.invokeNative(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419): at java.lang.reflect.Method.invoke(Method.java:515)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-18 19:27:28.558: E/AndroidRuntime(1419): at dalvik.system.NativeStart.main(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2035)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost.setCurrentTab(TabHost.java:413)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost.addTab(TabHost.java:240)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.Carnet.onCreate(Carnet.java:45)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419): ... 11 more
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.NoteAdapter.getCount(NoteAdapter.java:46)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.ListView.setAdapter(ListView.java:480)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.Note.onCreate(Note.java:34)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419): ... 21 more
Carnet.java line 45:
tabHost.addTab(NotaSpec);
NoteAdapter.java line 46:
return result.length;
Note.java line 34:
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
Your String array in null here:
NoteAdapter.java line 46:
return result.length;
because is a class field, you populate in the constructor from a parameter:
public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
// TODO Auto-generated constructor stub
result = prgmNameList;
that you pass as null here (passed as second parameter, it should be third):
Note.java line 34:
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
There is no point in passing that as a parameter as it is a public constant (public static final).
Related
I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful
Can someone point me out the error in this code. I am learning to code and I was trying to run my first app from tutorial I saw, until I found this message "Unfortunately, The New Boston has stopped". This the message I get when every time I tried to open it after installation. I even tried on three different phone and in my Emulator and the same thing happened. I looked at my code and I found no error on any line of code. And then I tried to debug it. Here is the entire code and the logcat report respectively.
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
int counter;
Button add,sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.sSub);
display = (TextView) findViewById(R.id.tvDisplat);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
display.setText("Your total is" + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
display.setText("Your total is" + counter);
}
});
}
}
#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
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Logcat output
07-18 21:28:21.047: E/AndroidRuntime(10601): FATAL EXCEPTION: main
07-18 21:28:21.047: E/AndroidRuntime(10601): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.thenewbostone/com.thenewbostone.MainActivity}: java.lang.NullPointerException
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.os.Handler.dispatchMessage(Handler.java:99)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.os.Looper.loop(Looper.java:123)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-18 21:28:21.047: E/AndroidRuntime(10601): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 21:28:21.047: E/AndroidRuntime(10601): at java.lang.reflect.Method.invoke(Method.java:521)
07-18 21:28:21.047: E/AndroidRuntime(10601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
07-18 21:28:21.047: E/AndroidRuntime(10601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
07-18 21:28:21.047: E/AndroidRuntime(10601): at dalvik.system.NativeStart.main(Native Method)
07-18 21:28:21.047: E/AndroidRuntime(10601): Caused by: java.lang.NullPointerException
07-18 21:28:21.047: E/AndroidRuntime(10601): at com.thenewbostone.MainActivity.onCreate(MainActivity.java:34)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-18 21:28:21.047: E/AndroidRuntime(10601): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-18 21:28:21.047: E/AndroidRuntime(10601): ... 11 more
You just have problem with this, sub should be on the second line, not add.
add = (Button) findViewById(R.id.bAdd);
add = (Button) findViewById(R.id.sSub);
So, it crashes then on this line
sub.setOnClickListener(new View.OnClickListener() {
cause sub wasn't initialized.
I tried to import an SQLite sample code into my Android application to save and manage my data through SQLite, using a ListView.
In this SQLite sample that implements an AddressBook when I fill in the text fields of a new contact and I press "Save" button to save them to my SQLite, then my Android app crashes, displaying that unfortunately my application has terminated.I believe that my problem is focused on the button Save(button1) and especially line: android:onClick="run" but I don't understand the exact problem.For your convenience method "run" is implemented in DisplayContact.java archive.
The code of my button1 in my activity_display_contact.xml layout is:
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editTextCity"
android:layout_alignParentBottom="true"
android:layout_marginBottom="28dp"
android:onClick="run"
android:text="#string/save" />
The code of my DisplayContact.java which is responsible for tha layout of ListView is :
package com.qualcomm.QCARSamples.ImageTargets;
import com.qualcomm.QCARSamples.ImageTargets1.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayContact extends Activity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView name ;
TextView phone;
TextView email;
TextView street;
TextView place;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_contact);
name = (TextView) findViewById(R.id.editTextName);
phone = (TextView) findViewById(R.id.editTextPhone);
email = (TextView) findViewById(R.id.editTextStreet);
street = (TextView) findViewById(R.id.editTextEmail);
place = (TextView) findViewById(R.id.editTextCity);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_NAME));
String phon = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_PHONE));
String emai = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_EMAIL));
String stree = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_STREET));
String plac = rs.getString(rs.getColumnIndex(DBHelper.CONTACTS_COLUMN_CITY));
if (!rs.isClosed())
{
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence)nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence)phon);
phone.setFocusable(false);
phone.setClickable(false);
email.setText((CharSequence)emai);
email.setFocusable(false);
email.setClickable(false);
street.setText((CharSequence)stree);
street.setFocusable(false);
street.setClickable(false);
place.setText((CharSequence)plac);
place.setFocusable(false);
place.setClickable(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
}
else{
getMenuInflater().inflate(R.menu.mainmenu, menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
name.setEnabled(true);
name.setFocusableInTouchMode(true);
name.setClickable(true);
phone.setEnabled(true);
phone.setFocusableInTouchMode(true);
phone.setClickable(true);
email.setEnabled(true);
email.setFocusableInTouchMode(true);
email.setClickable(true);
street.setEnabled(true);
street.setFocusableInTouchMode(true);
street.setClickable(true);
place.setEnabled(true);
place.setFocusableInTouchMode(true);
place.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),com.qualcomm.QCARSamples.ImageTargets.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view)
{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),com.qualcomm.QCARSamples.ImageTargets.MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else{
if(mydb.insertContact(name.getText().toString(), phone.getText().toString(), email.getText().toString(), street.getText().toString(), place.getText().toString())){
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),com.qualcomm.QCARSamples.ImageTargets.MainActivity.class);
startActivity(intent);
}
}
}
}
and the code of my Logcat is the following:
04-07 04:09:25.113: E/AndroidRuntime(7943): FATAL EXCEPTION: main
04-07 04:09:25.113: E/AndroidRuntime(7943): java.lang.IllegalStateException: Could not find a method run(View) in the activity class com.qualcomm.QCARSamples.ImageTargets.ImageTargets for onClick handler on view class android.widget.Button with id 'button1'
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.view.View$1.onClick(View.java:3050)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.view.View.performClick(View.java:3534)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.view.View$PerformClick.run(View.java:14263)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.os.Handler.handleCallback(Handler.java:605)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.os.Handler.dispatchMessage(Handler.java:92)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.os.Looper.loop(Looper.java:137)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.app.ActivityThread.main(ActivityThread.java:4441)
04-07 04:09:25.113: E/AndroidRuntime(7943): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 04:09:25.113: E/AndroidRuntime(7943): at java.lang.reflect.Method.invoke(Method.java:511)
04-07 04:09:25.113: E/AndroidRuntime(7943): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-07 04:09:25.113: E/AndroidRuntime(7943): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-07 04:09:25.113: E/AndroidRuntime(7943): at dalvik.system.NativeStart.main(Native Method)
04-07 04:09:25.113: E/AndroidRuntime(7943): Caused by: java.lang.NoSuchMethodException: run [class android.view.View]
04-07 04:09:25.113: E/AndroidRuntime(7943): at java.lang.Class.getConstructorOrMethod(Class.java:460)
04-07 04:09:25.113: E/AndroidRuntime(7943): at java.lang.Class.getMethod(Class.java:915)
04-07 04:09:25.113: E/AndroidRuntime(7943): at android.view.View$1.onClick(View.java:3043)
04-07 04:09:25.113: E/AndroidRuntime(7943): ... 11 more
This is weird: Your Java code creates an Activity called "DisplayContact" but the stacktrace says it cannot find an onClick handler called "run" in an Activity called "ImageTargets". I would check the way your development project has been set up.
Info: I am a decent java developer, I know my way around it pretty well I think, so I decided to give android a chance, and it hasn't been the smoothest road for me. I mess up very often. Anyway to my question if anyone would be so kind to help me out with this error I would very much appreciate it! Thank you.
Main Class
package dev.shaw.MyShoppingPlanner;
import java.io.File;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private String m_Text = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
if(firstTime()){
GenerateNeededFiles();
}
else{
//do nothing
}
ActionBar.TabListener tablistener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch(tab.getText().toString()){
case "Lists":
openLists();
break;
case "Store":
openStore();
case "Home":
openTab();
}
}
private void openTab() {
}
private void openStore() {
View v = new View(MainActivity.this);
v.setVisibility(1);
v.clearFocus();
v.bringToFront();
}
private void openLists() {
Intent intent = new Intent(MainActivity.this,List_Activity.class);
startActivity(intent);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// do nothing
}
};
actionbar.addTab(actionbar.newTab().setText("Home").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Store").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Lists").setTabListener(tablistener));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
private boolean firstTime() {
File storelist = new File(this.getFilesDir() + "\\StoreList.txt");
File listnames = new File(this.getFilesDir() + "\\ListNames.txt");
if(storelist.exists() && listnames.exists()){
return false;
}
else{
return true;
}
}
private void GenerateNeededFiles() {
Intent intent = new Intent(MainActivity.this,Install_Activity.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
default:
return super.onOptionsItemSelected(item);
}
}
private void openSettings() {
}
private void openSearch() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Search");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
The Class that gets an error when called
package dev.shaw.MyShoppingPlanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class List_Activity extends ListActivity {
String ListNames[] = getListNames();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem , ListNames));
}
protected void onListItemClick(ListView lv, View v, int pos,long id){
this.onListItemClick(lv, v, pos, id);
ShoppingList list = new ShoppingList(ListNames[pos]);
try {
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list.toArray(list.getFile())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String[] getListNames() {
File file = new File(this.getFilesDir() + "\\listnames.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStreamReader is = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(is);
String line;
String names[] = new String[100];
int i = 0;
try {
while(true){
line = br.readLine();
if(line == null){
break;
}
else{
try{
names[i] = line;
}
catch(NullPointerException e){
e.printStackTrace();
}
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return names;
}
}
and here is the printStack
03-23 04:58:16.523: D/dalvikvm(3710): GC_FOR_ALLOC freed 151K, 18% free 2770K/3356K, paused 2ms, total 7ms
03-23 04:58:16.531: D/dalvikvm(3710): GC_FOR_ALLOC freed 100K, 19% free 2988K/3680K, paused 1ms, total 4ms
03-23 04:58:16.535: I/dalvikvm-heap(3710): Grow heap (frag case) to 4.414MB for 1127532-byte allocation
03-23 04:58:16.539: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 3ms, total 3ms
03-23 04:58:16.555: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 1ms, total 1ms
03-23 04:58:16.587: I/dalvikvm-heap(3710): Grow heap (frag case) to 6.833MB for 2536932-byte allocation
03-23 04:58:16.599: D/dalvikvm(3710): GC_FOR_ALLOC freed 0K, 10% free 6567K/7264K, paused 2ms, total 2ms
03-23 04:58:16.615: D/HardwareRenderer(3710): Profiling hardware renderer
03-23 04:58:16.647: D/libEGL(3710): loaded /system/lib/egl/libEGL_genymotion.so
03-23 04:58:16.651: D/(3710): HostConnection::get() New Host Connection established 0xb85b3b40, tid 3710
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv2_genymotion.so
03-23 04:58:16.711: W/EGL_genymotion(3710): eglSurfaceAttrib not implemented
03-23 04:58:16.711: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from GradienCache
03-23 04:58:16.723: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
03-23 04:58:16.723: D/OpenGLRenderer(3710): Enabling debug mode 0
03-23 04:58:18.015: D/AndroidRuntime(3710): Shutting down VM
03-23 04:58:18.015: W/dalvikvm(3710): threadid=1: thread exiting with uncaught exception (group=0xa4bae648)
03-23 04:58:18.015: E/AndroidRuntime(3710): FATAL EXCEPTION: main
03-23 04:58:18.015: E/AndroidRuntime(3710): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{dev.shaw.MyShoppingPlanner/dev.shaw.MyShoppingPlanner.List_Activity}: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Handler.dispatchMessage(Handler.java:99)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Looper.loop(Looper.java:137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invokeNative(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invoke(Method.java:525)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dalvik.system.NativeStart.main(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): Caused by: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.content.ContextWrapper.getFilesDir(ContextWrapper.java:199)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.getListNames(List_Activity.java:38)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.<init>(List_Activity.java:16)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstanceImpl(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstance(Class.java:1130)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
03-23 04:58:18.015: E/AndroidRuntime(3710): ... 11 more
This is my Login.java code
package com.pmss;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Login extends Activity {
Button login, register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.register);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//startActivity(new Intent());
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(new Intent(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.login, menu);
return true;
}
}
This is my Register.java
package com.pmss;
import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Register extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.pmss.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
/*MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.register, menu);
return super.onCreateOptionsMenu(menu);*/
getMenuInflater().inflate(R.menu.register, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setIconifiedByDefault(false);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, RegisterNextPart.class);
EditText editText = (EditText) findViewById(R.id.nametext);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openSearch(){
}
public void openSettings(){
}
}
I wonder is it anything to do with this coding:
register = (Button) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(new Intent(intent));
}
});
When run on my mobile phone and I tap register button which end up force close the application. Anybody help me? really new to ADT
And This is my logcat
11-23 22:09:32.029: W/dalvikvm(15739): VFY: unable to resolve interface method 7433: Landroid/view/MenuItem;.getActionView ()Landroid/view/View;
11-23 22:09:32.169: D/AndroidRuntime(15739): Shutting down VM
11-23 22:09:32.169: W/dalvikvm(15739): threadid=1: thread exiting with uncaught exception (group=0x40018578)
11-23 22:09:32.169: E/AndroidRuntime(15739): FATAL EXCEPTION: main
11-23 22:09:32.169: E/AndroidRuntime(15739): java.lang.NoSuchMethodError: android.view.MenuItem.getActionView
11-23 22:09:32.169: E/AndroidRuntime(15739): at com.pmss.Register.onCreateOptionsMenu(Register.java:36)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.app.Activity.onCreatePanelMenu(Activity.java:2158)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:70)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.os.Handler.handleCallback(Handler.java:587)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.os.Handler.dispatchMessage(Handler.java:92)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.os.Looper.loop(Looper.java:130)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.app.ActivityThread.main(ActivityThread.java:3687)
11-23 22:09:32.169: E/AndroidRuntime(15739): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 22:09:32.169: E/AndroidRuntime(15739): at java.lang.reflect.Method.invoke(Method.java:507)
11-23 22:09:32.169: E/AndroidRuntime(15739): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-23 22:09:32.169: E/AndroidRuntime(15739): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-23 22:09:32.169: E/AndroidRuntime(15739): at dalvik.system.NativeStart.main(Native Method)
Change your register button setOnClickListener code to
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
}
});
And Don't Forget to add Activity in your Manifest File
<activity
android:name=".Register"
android:label="#string/app_name">
</activity>
Ther are so many cases why this error is occured.
1) May be you have forgot to add Register activity to your Menifest File.
2) The ID which you are providing for registed is wrong
and so other also, It's very hard to tell without logcat. But this are cases which might occur.