There is a NPE at the last line, I can't figure out where it's coming from. Any ideas?
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
listContent = (ListView)findViewById(R.id.contentlist);
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[]{SQLiteAdapter.KEY_CHOICE,
SQLiteAdapter.KEY_AMOUNT};
int[] to = new int[]{R.id.txtChoice, R.id.txtAmtSpent};
SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row2, cursor, from, to);
mySQLiteAdapter.close();
listContent.setAdapter(cursorAdapter);
HERE IS THE ERROR
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): FATAL EXCEPTION: main
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.whycom.idontknow/com.whycom.idontknow.ListSpent}: java.lang.NullPointerException
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at android.os.Handler.dispatchMessage(Handler.java:99)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at android.os.Looper.loop(Looper.java:123)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at java.lang.reflect.Method.invokeNative(Native Method)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at java.lang.reflect.Method.invoke(Method.java:521)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at dalvik.system.NativeStart.main(Native Method)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): Caused by: java.lang.NullPointerException
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at com.whycom.idontknow.ListSpent.makeList(ListSpent.java:161)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at com.whycom.idontknow.ListSpent.onCreate(ListSpent.java:79)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
06-19 01:27:50.832: ERROR/AndroidRuntime(1425): ... 11 more
The whole code is below:
package com.whycom.idontknow;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ListSpent extends ListActivity {
private SQLiteAdapter mySQLiteAdapter;
//Intent splat;
//Bundle b;
// String[] amounts;
// String[] expenditureArray;
String choice;
String amount;
int count;
String[] dataAry= new String[100];
//String[] choices;
String Count;
SharedPreferences prefs;
TextView txtAmtSpent;
TextView txtChoice;
ListAdapter adapter;
ListView listContent;
int j;
// ListView listContent;
// PreferenceManager.getDefaultSharedPreferences(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlist);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
//ListView listContent = (ListView)findViewById(R.id.contentlist);
initVars();
try {
buildArray();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
makeList();
}
static class ViewHolder{
TextView text;
TextView button;
}
public void buildArray() throws IOException{
//ArrayList<String> al = new ArrayList<String>();
InputStream instream;
try {
instream = openFileInput("mySpends.txt");
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
Count = prefs.getString("Count" , "0");
count = Integer.parseInt(Count);
for (int i = 0; i < ((count)*2); i=i+2){
choice = buffreader.readLine();
amount = buffreader.readLine();
dataAry[i] = choice;
dataAry[i+1] = amount;
//trial
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private void initVars(){
txtAmtSpent = (TextView)findViewById(R.id.txtAmtSpent);
txtChoice = (TextView)findViewById(R.id.txtChoice);
listContent = (ListView)findViewById(R.id.contentlist);
}
private void makeList(){
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();
ListView listContent = (ListView)findViewById(R.id.contentlist);
String [] dataAryArray = new String[(count)*2];
j = 0;
int ind = (count)*2-1;
for (int i = -1; i < ind; ind = ind - 2){
dataAryArray[j] = dataAry[ind];
dataAryArray[j+1] = dataAry[ind-1];
mySQLiteAdapter.insert(dataAryArray[j],dataAryArray[j+1]);
j=j+2;
}
mySQLiteAdapter.close();
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String c=SQLiteAdapter.KEY_CHOICE;
String a=SQLiteAdapter.KEY_AMOUNT;
String[] from = new String[]{SQLiteAdapter.KEY_CHOICE, SQLiteAdapter.KEY_AMOUNT};
int[] to = new int[]{R.id.txtChoice, R.id.txtAmtSpent};
SimpleCursorAdapter cursorAdapter =
new SimpleCursorAdapter(this, R.id.text, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
// adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, dataAryArray);
// setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Toast",
Toast.LENGTH_SHORT).show();
}
}
)
;
}
}
Here is the XML named mainlist.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
listContent is not found.
You may need to call setContentView before trying findViewById.
Update
Based on more information and provided code, since your declared ListView id
android:id="#android:id/list"
it refers to Android id not your own. So you need to search for it via
findViewById(android.R.id.list)
not your package R.
But why would you even need it if ListActivity provides all methods so you don't have to access it directly? For example,
setListAdapter(...);
See example here http://www.higherpass.com/Android/Tutorials/Creating-Lists-Using-The-Android-Listactivity/
It would be really helpful to include the stack trace for the NPE. But I suspect the problem might be this line, immediately before the NPE:
mySQLiteAdapter.close();
If the SQLiteAdapter class is similar to the NotesDbAdapter class from the Android Notepad tutorial, then you shouldn't be closing it there; that will invalidate your cursor. Instead, close it in your activity's onDestroy method. (That last link goes to a blog post that I wrote regarding when and how to close these objects.)
Related
package com.example.cyber.sayac_say;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
int count;
Button btn;
SharedPreferences ayarlar = null;
RelativeLayout arkaplan;
Boolean ses_durumu, titresim_durumu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ayarlar = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
ayarlariYukle();
btn = (Button) findViewById(R.id.button);
arkaplan = (RelativeLayout) findViewById(R.id.rl);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
btn.setText(""+count);
}
});
}
hi , this is my codes. And when I used Shared Preferences so I have this error.But when I erase shared preferences lines so error is gone.
The problem is about Shared Prefenrences.I definitely sure.
What can I do before crazy:)?
03-22 14:16:23.972 6613-6613/com.example.cyber.sayac_say
E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cyber.sayac_say/com.example.cyber.sayac_say.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.cyber.sayac_say.MainActivity.ayarlariYukle(MainActivity.java:76)
at com.example.cyber.sayac_say.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I am trying to display an array of strings in a list view. the app crashes saying null pointer exception but it does not specify the line in which null pointer occurs.
ReportHistoryFragment:-
package com.appdev.ngoapp;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.Iterator;
import java.util.List;
/**
* Created by Adarsh on 01-02-2015.
*/
public class ReportHistoryFragment extends Fragment {
View reportHistory;
ParseUser parseUser;
ParseQuery<ParseObject> parseQuery,pq;
ParseObject parseObject;
String[] title;
Context context;
ArrayAdapter<String> stringArrayAdapter;
ListView listView;
int size,i=0;
ProgressDialog progressDialog;
Iterator<ParseObject> iterator;
public ReportHistoryFragment(Context context) {
this.context=context;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
reportHistory = inflater.inflate(R.layout.report_history_layout,container,false);
listView = (ListView) reportHistory.findViewById(R.id.list_history);
return reportHistory;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
parseUser = ParseUser.getCurrentUser();
progressDialog = ProgressDialog.show(context,"Downloading Data","Please wait...",true);
progressDialog.setCancelable(false);
downloadData();
}
public void downloadData() {
parseQuery = ParseQuery.getQuery("Reports");
parseQuery.whereEqualTo("user",parseUser);
parseQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if (e == null) {
iterator = parseObjects.iterator();
size = parseObjects.size();
title = new String[size];
i=0;
while (iterator.hasNext()) {
parseObject = iterator.next();
pq = ParseQuery.getQuery("Reports");
Log.v("ID",parseObject.getObjectId());
pq.getInBackground(parseObject.getObjectId(), new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
title[i] = object.getString("title");
i++;
} else {
e.printStackTrace();
}
if(i==size-1) {
stringArrayAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,title);
listView.setAdapter(stringArrayAdapter);
}
}
});
}
} else {
e.printStackTrace();
}
}
});
}
}
report_history_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_history">
</ListView>
</RelativeLayout>
Logcat
02-03 20:34:07.780 18717-18717/com.appdev.ngoapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.appdev.ngoapp, PID: 18717
java.lang.NullPointerException
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsListView.obtainView(AbsListView.java:2255)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
at android.widget.ListView.onMeasure(ListView.java:1175)
at android.view.View.measure(View.java:16521)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16521)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16521)
at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:851)
at android.view.View.measure(View.java:16521)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16521)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16521)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1450)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16521)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16521)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1450)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16521)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2552)
at android.view.View.measure(View.java:16521)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1915)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5603)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
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:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Check if you're actually putting anything in your title array. Then check whether stringArrayAdapter is initializing properly.
I am trying to pass a String form one activity to another in my app, however I keep getting a null pointer error. This is what shows up in my LogCat:
12-29 02:49:03.256: D/(663): HostConnection::get() New Host Connection established 0x96cb850, tid 663
12-29 02:49:06.288: W/KeyCharacterMap(663): No keyboard for id 0
12-29 02:49:06.288: W/KeyCharacterMap(663): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
12-29 02:49:09.600: D/AndroidRuntime(663): Shutting down VM
12-29 02:49:09.600: W/dalvikvm(663): threadid=1: thread exiting with uncaught exception (group=0xb5f444f0)
12-29 02:49:09.604: E/AndroidRuntime(663): FATAL EXCEPTION: main
12-29 02:49:09.604: E/AndroidRuntime(663): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld3/com.example.helloworld3.FloorPlan}: java.lang.NullPointerException
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.os.Handler.dispatchMessage(Handler.java:99)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.os.Looper.loop(Looper.java:130)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-29 02:49:09.604: E/AndroidRuntime(663): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 02:49:09.604: E/AndroidRuntime(663): at java.lang.reflect.Method.invoke(Method.java:507)
12-29 02:49:09.604: E/AndroidRuntime(663): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-29 02:49:09.604: E/AndroidRuntime(663): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-29 02:49:09.604: E/AndroidRuntime(663): at dalvik.system.NativeStart.main(Native Method)
12-29 02:49:09.604: E/AndroidRuntime(663): Caused by: java.lang.NullPointerException
12-29 02:49:09.604: E/AndroidRuntime(663): at com.example.helloworld3.FloorPlan.onCreate(FloorPlan.java:24)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-29 02:49:09.604: E/AndroidRuntime(663): ... 11 more
12-29 02:49:12.316: D/(677): HostConnection::get() New Host Connection established 0x96c5790, tid 677
This is my ManActivity.java:
package com.example.helloworld3;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract.RawContacts.Data;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText destination = (EditText)findViewById(R.id.roomdinput);
final Button floorPlan = (Button)findViewById(R.id.floorPlanButton);
floorPlan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
String roomName = destination.getText().toString();
Bundle myb = new Bundle();
myb.putString("key1", roomName);
Intent a = new Intent(MainActivity.this, FloorPlan.class);
a.putExtras(myb);
startActivity(a);
startActivity(new Intent("com.example.helloworld3.FLOORPLAN"));
}
});
}
#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);
}
}
And this is my FloorPan.java:
package com.example.helloworld3;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FloorPlan extends Activity{
DrawView2 drawView;
String roomName2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.floorplan);
Bundle myb2= getIntent().getExtras();
roomName2 = myb2.getString("key1");
drawView = new DrawView2(this);
drawView.setBackgroundResource(R.drawable.tait1st);
setContentView(drawView);
}
public class DrawView2 extends View {
Paint paint = new Paint();
float ux, dx, rx,lx;
public String getRoomName(){
return roomName2;
}
public void setCoordinates(){
if(roomName2 == "C154"){
ux =90;
dx = 250;
rx = 90;
lx = 400;
}else {
ux =76;
dx = 98;
rx = 140;
lx = 300;
}
};
public DrawView2(Context context) {
super(context);
paint.setColor(Color.RED);
//roomName2 = drawView.getTag();
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawLine(ux, dx , rx, lx, paint);
canvas.drawLine(20, 0, 0, 20, paint);
canvas.drawCircle(150, 400, 30, paint);
}
}
}
Thank you for all your help!
I think , This line in OnClickListener of floorPlan in your MainActivity causing problem :
startActivity(new Intent("com.example.helloworld3.FLOORPLAN"));
putString method is correct. It's inherited from android.os.BaseBundle.
The logcat shows your bundle get from intent.getExtras() is null:
Bundle myb2= getIntent().getExtras();
roomName2 = myb2.getString("key1");//here myb2 is null
Maybe you should override onNewIntent to setIntent:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
Why you have started activity 2 times in below code ?
Intent a = new Intent(MainActivity.this, FloorPlan.class);
a.putExtras(myb); startActivity(a);
startActivity(new Intent("com.example.helloworld3.FLOORPLAN")); // this intent doesnt`t have bundle
This might be the reason which lead where Bundle object is null in intent and causing nullpointerexception.
I am getting a NullPointerException. Below you can find my Logcat and the relevant code.
Logcat:
12-23 00:17:35.330: E/AndroidRuntime(2019): FATAL EXCEPTION: main
12-23 00:17:35.330: E/AndroidRuntime(2019): Process: com.android.timesheet, PID: 2019
12-23 00:17:35.330: E/AndroidRuntime(2019): java.lang.NullPointerException
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.timesheet.adapter.CustomCursorAdapter$1.onClick(CustomCursorAdapter.java:54)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View.performClick(View.java:4438)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.view.View$PerformClick.run(View.java:18422)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.handleCallback(Handler.java:733)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Handler.dispatchMessage(Handler.java:95)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.os.Looper.loop(Looper.java:136)
12-23 00:17:35.330: E/AndroidRuntime(2019): at android.app.ActivityThread.main(ActivityThread.java:5017)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invokeNative(Native Method)
12-23 00:17:35.330: E/AndroidRuntime(2019): at java.lang.reflect.Method.invoke(Method.java:515)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-23 00:17:35.330: E/AndroidRuntime(2019): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-23 00:17:35.330: E/AndroidRuntime(2019): at dalvik.system.NativeStart.main(Native Method)
CustomCursorAdapter.java:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.android.timesheet.ModifyMember;
import com.android.timesheet.R;
public class CustomCursorAdapter extends CursorAdapter {
Button delete_btn;
TextView memID_tv, memName_tv;
#SuppressWarnings("deprecation")
public CustomCursorAdapter(Activity context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
return retView;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
memID_tv = (TextView)v.findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
String memberID_val = memID_tv.getText().toString();; ---->54th Line
String memberName_val = memName_tv.getText().toString();
Intent i = new Intent(context,
ModifyMember.class);
i.putExtra("memberName", memberName_val);
i.putExtra("memberID", memberID_val);
((Activity)context).startActivity(i);
}
});
}
}
I am using a delete button to delete all the listview row items. At that point I am getting the NullPointerException.
Use view(view of row) instead of v parameter of onClick method which is view of Button :
delete_btn=(Button)view.findViewById(R.id.delete_btn);
delete_btn.setTag(view);
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View rowview=(View)v.getTag();
memID_tv = (TextView)rowview.findViewById(R.id.member_id);
memName_tv = (TextView)rowview.findViewById(R.id.member_name);
}
});
Use view instead of v
memID_tv = (TextView)view.findViewById(R.id.member_id);
In bindview try this-
if (view == null) {
view = inflater.inflate(R.layout.single_row_item, parent, null);
}
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
delete_btn=(Button)view.findViewById(R.id.delete_btn);
.
.
.
you are getting the view from clicked view, but you have to get the views from the root view.
memID_tv = (TextView)v. findViewById(R.id.member_id);
memName_tv = (TextView)v.findViewById(R.id.member_name);
change these lines into this:
memID_tv = (TextView)view. findViewById(R.id.member_id);
memName_tv = (TextView)view.findViewById(R.id.member_name);
My main Activity
package com.std.stunduizmainas;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import com.std.adapter.SSS;
import com.std.adapter.TabsPagerAdapter;
import com.std.stunduizmainas.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
public static String izm;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
SharedPreferences settings;
Spinner skoluSp;
Spinner klasuSp;
Spinner izvSp;
static String info="";
static String rinfo="";
Dialog fb;
static String sd="";
static String rd="";
List<String> ssk = new ArrayList<String>();
List<String> person = new ArrayList<String>();
List<String> skl = new ArrayList<String>();
List<String> tabi = new ArrayList<String>();
String[] techerorstudent = new String[]{"Skolēns","Skolotājs"};
static String[] tabs = new String[4];
static String regid="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.enableDefaults();
getActionBar().setTitle("Stundu");
getActionBar().setSubtitle("izmainas");
settings = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
getTab();
startService(new Intent(this,SSS.class));
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//tabs
for (String tab_name : tabi) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
and my TabsPagerAdapter
package com.std.adapter;
import com.std.stunduizmainas.KlasesIzm;
import com.std.stunduizmainas.RitdienasIzm;
import com.std.stunduizmainas.SkolasIzm;
import com.std.stunduizmainas.Paz;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new SkolasIzm();
case 1:
// Games fragment activity
return new RitdienasIzm();
case 2:
// Movies fragment activity
return new Paz();
case 3:
return new KlasesIzm();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
});
}
I can't seem to be able to figure out what's the problem. I know that it is with this line of code viewPager.setAdapter(mAdapter);.
The log cat shows this as an error:
03-04 17:45:48.092: E/AndroidRuntime(1880): FATAL EXCEPTION: main
03-04 17:45:48.092: E/AndroidRuntime(1880): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.std.stunduizmainas/com.std.stunduizmainas.MainActivity}: java.lang.NullPointerException
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.os.Handler.dispatchMessage(Handler.java:99)
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.os.Looper.loop(Looper.java:137)
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-04 17:45:48.092: E/AndroidRuntime(1880): at java.lang.reflect.Method.invokeNative(Native Method)
03-04 17:45:48.092: E/AndroidRuntime(1880): at java.lang.reflect.Method.invoke(Method.java:525)
03-04 17:45:48.092: E/AndroidRuntime(1880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-04 17:45:48.092: E/AndroidRuntime(1880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-04 17:45:48.092: E/AndroidRuntime(1880): at dalvik.system.NativeStart.main(Native Method)
03-04 17:45:48.092: E/AndroidRuntime(1880): Caused by: java.lang.NullPointerException
03-04 17:45:48.092: E/AndroidRuntime(1880): at com.std.stunduizmainas.MainActivity.onCreate(MainActivity.java:132)
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.app.Activity.performCreate(Activity.java:5133)
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-04 17:45:48.092: E/AndroidRuntime(1880): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
03-04 17:45:48.092: E/AndroidRuntime(1880): ... 11 more
Could anybody please help me?
Looks like your viewPager is null.
Make sure the ID used in this line:
viewPager = (ViewPager) findViewById(R.id.pager);
is valid and references a viewpager in your activity_main.xml layout.