ViewPager nullPointerException error - java

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.

Related

SharedPreferences in Android AndroidRunTime Exception and NullPointerException

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) 

Nullpointerexception listview android

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.

Using/understanding Alarm manager force close [Android]

My android app keeps force closing, due to the recent addition of Alarm manager. I am new to alarm manager and did what i did with parts of tutorials. In the code i have said where i have put my 'doing code' (not sure if this is the right place?). Pls also mention where i should put other parts of my code, that are not affected be alarm manager.
Here is my logcat:
04-16 14:36:52.011: E/AndroidRuntime(1127): FATAL EXCEPTION: main
04-16 14:36:52.011: E/AndroidRuntime(1127): Process: com.knight, PID: 1127
04-16 14:36:52.011: E/AndroidRuntime(1127): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.knight./com.knight.MainActivity}: java.lang.NullPointerException
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.os.Handler.dispatchMessage(Handler.java:102)
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.os.Looper.loop(Looper.java:136)
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-16 14:36:52.011: E/AndroidRuntime(1127): at java.lang.reflect.Method.invokeNative(Native Method)
04-16 14:36:52.011: E/AndroidRuntime(1127): at java.lang.reflect.Method.invoke(Method.java:515)
04-16 14:36:52.011: E/AndroidRuntime(1127): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-16 14:36:52.011: E/AndroidRuntime(1127): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-16 14:36:52.011: E/AndroidRuntime(1127): at dalvik.system.NativeStart.main(Native Method)
04-16 14:36:52.011: E/AndroidRuntime(1127): Caused by: java.lang.NullPointerException
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:173)
04-16 14:36:52.011: E/AndroidRuntime(1127): at com.knight.MainActivity.<init>(MainActivity.java:44)
04-16 14:36:52.011: E/AndroidRuntime(1127): at java.lang.Class.newInstanceImpl(Native Method)
04-16 14:36:52.011: E/AndroidRuntime(1127): at java.lang.Class.newInstance(Class.java:1208)
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
04-16 14:36:52.011: E/AndroidRuntime(1127): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
04-16 14:36:52.011: E/AndroidRuntime(1127): ... 11 more
04-16 14:36:56.491: I/Process(1127): Sending signal. PID: 1127 SIG: 9
Here is my Alarm.java:
package com.knight.;
import java.util.Random;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.widget.TextView;
import android.app.Service;
public class Alarm extends Service{
public void onStart(Intent intent, int startId) {
{
//MY CODE????
}
}
private TextView findViewById(int textview3) {
// TODO Auto-generated method stub
return null;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Here is the alarm setup java:
package com.knight.;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.Calendar;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import com.knight..R;
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Intent myIntent = new Intent(MainActivity.this, Alarm.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.set(Calendar.HOUR_OF_DAY, 0, pendingIntent);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
// time set up is unsuccessful in earlier versions
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

SQLite + setAdapter = NPE

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

Error while running the android project in eclipse run time error

05-05 14:32:25.210: ERROR/AndroidRuntime(551): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.org.pc/com.org.pc.Login}: java.lang.NullPointerException
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.os.Handler.dispatchMessage(Handler.java:99)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.os.Looper.loop(Looper.java:123)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.main(ActivityThread.java:4363)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at java.lang.reflect.Method.invokeNative(Native Method)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at java.lang.reflect.Method.invoke(Method.java:521)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at dalvik.system.NativeStart.main(Native Method)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): Caused by: java.lang.NullPointerException
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at com.org.pc.Login.loginDetails(Login.java:116)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at com.org.pc.Login.onCreate(Login.java:54)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-05 14:32:25.210: ERROR/AndroidRuntime(551): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
the code is :
package com.org.pc;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
public class Login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Login","Reached");
Log.i("Login","View set");
Bitmap bitmap = (Bitmap) this.getIntent().getParcelableExtra("BitmapImage");
if(bitmap==null)
Log.v("Sdrawable","null");
else
Log.v("Sdrawable","not null");
loginDetails();
setContentView(R.layout.view);
ImageView viewBitmap = (ImageView)findViewById(R.id.bitmapview);
viewBitmap.setImageBitmap(bitmap);
Button login=(Button) findViewById(R.id.login);
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
username = pref.getString(PREF_USERNAME, null);
password = pref.getString(PREF_PASSWORD, null);
if(username != null && password != null)
{
Log.v("username",username);
//user.setText(username);
//pass.setText(password);
}
login.setOnClickListener(new Button.OnClickListener()
{
public void onClick (View v)
{
setContentView(R.layout.home);
}
});
}
public static final String PREFS_NAME = "PrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";
public String username = null;
public String password = null;
//EditText user = (EditText)findViewById(R.id.username);
//EditText pass = (EditText)findViewById(R.id.password);
public void loginDetails()
{
if (username == null || password == null)
{
// username = user.getText().toString();
// password = pass.getText().toString();
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://69.10.60.88:88/BZLogin.aspx");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", "abdul"));
nameValuePairs.add(new BasicNameValuePair("password", "abdul"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
CheckBox cb = (CheckBox)findViewById(R.id.remember);
if ( cb.isChecked() )
{
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, username)
.putString(PREF_PASSWORD, password)
.commit();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
You're calling loginDetails() before you have inflated your layout to the activity. So, no ui elements exist. call setContentView() before you call findViewById().
You called CheckBox cb = (CheckBox)findViewById(R.id.remember) before setContentView(R.layout.view). That's may be why.
Call loginDetails() after setContentView(R.layout.view).

Categories