Force Close java.lang.RuntimeException: Unable to start activity - java

I am using methods to shorten my onCreate method
But When I'm trying my app I got force close!
Help please to solve this problem
Activity Class (Main):
package ir.TeenStudio.ActivitiesManagement;
import java.util.ArrayList;
import java.util.HashMap;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;
public class Main extends Activity {
public static SQLiteDatabase ActivitiesListDatabase;
private SlidingMenu slidingMenu;
private ActivitiesExpandableListAdapter activitiesListViewAdapter;
private ArrayList<String> groupsList;
private HashMap<String, ArrayList<HashMap<String, String>>> childsList;
private ArrayList<HashMap<String,String>> todayChildsList;
private ArrayList<HashMap<String,String>> tomarrowChildsList;
private ArrayList<HashMap<String,String>> futureChildsList;
private ArrayList<HashMap<String,String>> oneDayChildsList;
private ExpandableListView mylist;
private TextView DayTextView;
private TextView MonthTextView;
private TextView YearTextView;
private Button mainActivity;
private Button ListActivity;
private Button Setting;
private Button Contact;
private Button Information;
private ImageButton Menu;
private ImageButton Add;
private Typeface Rezvan;
private Typeface DroidNaskh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
slidingMenu = new SlidingMenu(this);
activitiesListViewAdapter = new ActivitiesExpandableListAdapter(Main.this, groupsList, childsList);
groupsList = new ArrayList<String>();
childsList = new HashMap<String, ArrayList<HashMap<String,String>>>();
todayChildsList = new ArrayList<HashMap<String,String>>();
tomarrowChildsList = new ArrayList<HashMap<String,String>>();
futureChildsList = new ArrayList<HashMap<String,String>>();
oneDayChildsList = new ArrayList<HashMap<String,String>>();
mylist = (ExpandableListView) findViewById(R.id.activitiesListView);
DayTextView = (TextView) findViewById(R.id.day);
MonthTextView = (TextView) findViewById(R.id.month);
YearTextView = (TextView) findViewById(R.id.year);
mainActivity = (Button) findViewById(R.id.button_main_activity);
ListActivity = (Button) findViewById(R.id.button_lists_activity);
Setting = (Button) findViewById(R.id.button_setting);
Contact = (Button) findViewById(R.id.button_contact);
Information = (Button) findViewById(R.id.button_info);
Menu = (ImageButton) findViewById(R.id.menu_button);
Add = (ImageButton) findViewById(R.id.add_button);
Rezvan = Typeface.createFromAsset(getAssets(), "fonts/rezvan.ttf");
DroidNaskh = Typeface.createFromAsset(getAssets(), "fonts/droid_naskh.ttf");
// Sliding Menu
setSlidingMenu();
//TypoGraphy
setLayoutTypoGraphy();
//LayoutProgramming
setTime();
setButtonsEvent();
//Creating Database
try {
final String path = Environment.getDataDirectory() +"/data/" + getPackageName() + "/ActivitiesList.db";
ActivitiesListDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.CREATE_IF_NECESSARY);
String query ="CREATE TABLE IF NOT EXISTS Content(";
query += "Id INTEGER PRIMARY KEY AUTOINCREMENT,";
query += "Description TEXT,";
query += "AddLocation INTEGER,";
query += "Location TEXT,";
query += "AddDate INTEGER,";
query += "DateYear INTEGER,";
query += "DateMonth INTEGER,";
query += "DateDay INTEGER,";
query += "AddHour INTEGER,";
query += "Hour INTEGER,";
query += "Minutes INTEGER,";
query += "AddAlarm INTEGER,";
query += "AlarmTime INTEGER,";
query += "AddSpecial INTEGER)";
ActivitiesListDatabase.execSQL(query);
Log.d("Database", "Database Created");
} catch (Exception e) {
Log.e("Database", "Database Error");
}
//Receive Data From Database
receiveDataFromDatabase();
//Sending Data to ListView
mylist.setAdapter(activitiesListViewAdapter);
}
#Override
protected void onResume() {
super.onResume();
receiveDataFromDatabase();
activitiesListViewAdapter.notifyDataSetChanged();
}
public void setLayoutTypoGraphy() {
DayTextView.setTypeface(Rezvan);
MonthTextView.setTypeface(Rezvan);
YearTextView.setTypeface(Rezvan);
mainActivity.setTypeface(DroidNaskh);
ListActivity.setTypeface(DroidNaskh);
Setting.setTypeface(DroidNaskh);
Contact.setTypeface(DroidNaskh);
Information.setTypeface(DroidNaskh);
}
public void setTime() {
DayTextView.setText(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getDay());
YearTextView.setText(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getYear());
int solarMonth = Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getMonth());
switch (solarMonth) {
case 1:
MonthTextView.setText("فروردین");
break;
case 2:
MonthTextView.setText("اردیبهشت");
break;
case 3:
MonthTextView.setText("خرداد");
break;
case 4:
MonthTextView.setText("تیر");
break;
case 5:
MonthTextView.setText("مرداد");
break;
case 6:
MonthTextView.setText("شهریور");
break;
case 7:
MonthTextView.setText("مهر");
break;
case 8:
MonthTextView.setText("آبان");
break;
case 9:
MonthTextView.setText("آذر");
break;
case 10:
MonthTextView.setText("دی");
break;
case 11:
MonthTextView.setText("بهمن");
break;
case 12:
MonthTextView.setText("اسفند");
break;
}
}
public void receiveDataFromDatabase() {
groupsList.clear();
childsList.clear();
todayChildsList.clear();
tomarrowChildsList.clear();
futureChildsList.clear();
oneDayChildsList.clear();
groupsList.add("امروز");
groupsList.add("فردا");
groupsList.add("آینده");
groupsList.add("یه روز");
Cursor cr = ActivitiesListDatabase.rawQuery("SELECT * FROM Content", null);
if (cr.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Description", cr.getString(cr.getColumnIndex("Description")));
map.put("AddDate", cr.getString(cr.getColumnIndex("AddDate")));
map.put("AddLocation", cr.getString(cr.getColumnIndex("AddLocation")));
map.put("Location", cr.getString(cr.getColumnIndex("Location")));
map.put("DateYear", cr.getString(cr.getColumnIndex("DateYear")));
map.put("DateMonth", cr.getString(cr.getColumnIndex("DateMonth")));
map.put("DateDay", cr.getString(cr.getColumnIndex("DateDay")));
map.put("AddHour", cr.getString(cr.getColumnIndex("AddHour")));
map.put("Hour", cr.getString(cr.getColumnIndex("Hour")));
map.put("Minutes", cr.getString(cr.getColumnIndex("Minutes")));
map.put("AddAlarm", cr.getString(cr.getColumnIndex("AddAlarm")));
map.put("AlarmTime", cr.getString(cr.getColumnIndex("AlarmTime")));
map.put("AddSpecial", cr.getString(cr.getColumnIndex("AddSpecial")));
if (Integer.parseInt(cr.getString(cr.getColumnIndex("AddDate")))==1) {
if(Integer.parseInt(cr.getString(cr.getColumnIndex("DateYear")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getYear())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateMonth")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getMonth())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateDay")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getDay())){
todayChildsList.add(map);
}
else if (Integer.parseInt(cr.getString(cr.getColumnIndex("DateYear")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getYear())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateMonth")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getMonth())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateDay")))==(Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getDay()))+1) {
tomarrowChildsList.add(map);
}
else {
futureChildsList.add(map);
}
} else oneDayChildsList.add(map);
} while (cr.moveToNext());
}
childsList.put(groupsList.get(0), todayChildsList);
childsList.put(groupsList.get(1), tomarrowChildsList);
childsList.put(groupsList.get(2), futureChildsList);
childsList.put(groupsList.get(3), oneDayChildsList);
}
public void setSlidingMenu() {
slidingMenu.setMode(SlidingMenu.RIGHT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setShadowDrawable(R.drawable.menu_shadow);
slidingMenu.setShadowWidth(30);
slidingMenu.setFadeDegree(1.0f);
slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
int menu_width = width - width / 3;
if (menu_width < 100) {
menu_width = 100;
}
slidingMenu.setBehindWidth(menu_width);
slidingMenu.setMenu(R.layout.main_right);
}
public void setButtonsEvent() {
OnClickListener ButtonsEvents = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.menu_button:
slidingMenu.toggle();
break;
case R.id.add_button:
Intent popUpAddItemDialogActivity = new Intent(Main.this, AddItem.class);
startActivity(popUpAddItemDialogActivity);
break;
case R.id.button_main_activity:
//Start main activity
break;
case R.id.button_lists_activity:
//Start lists activity
break;
case R.id.button_setting:
//Start setting
break;
case R.id.button_contact:
//Start contact activity
break;
case R.id.button_info:
//Start info activity
break;
default:
break;
}
}
};
Menu.setOnClickListener(ButtonsEvents);
Add.setOnClickListener(ButtonsEvents);
}
}
And this is my Manifest Code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.TeenStudio.ActivitiesManagement"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/name_application"
android:theme="#style/AppTheme" >
<activity
android:name="ir.TeenStudio.ActivitiesManagement.Splash"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="ir.TeenStudio.ActivitiesManagement.Main" android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen">
</activity>
<activity android:theme="#android:style/Theme.Dialog" android:name="AddItem"></activity>
</application>
</manifest>
Log
08-24 22:10:53.325: E/AndroidRuntime(2144): FATAL EXCEPTION: main
08-24 22:10:53.325: E/AndroidRuntime(2144): Process: ir.TeenStudio.ActivitiesManagement, PID: 2144
08-24 22:10:53.325: E/AndroidRuntime(2144): java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.TeenStudio.ActivitiesManagement/ir.TeenStudio.ActivitiesManagement.Main}: java.lang.NullPointerException
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.os.Handler.dispatchMessage(Handler.java:102)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.os.Looper.loop(Looper.java:136)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-24 22:10:53.325: E/AndroidRuntime(2144): at java.lang.reflect.Method.invokeNative(Native Method)
08-24 22:10:53.325: E/AndroidRuntime(2144): at java.lang.reflect.Method.invoke(Method.java:515)
08-24 22:10:53.325: E/AndroidRuntime(2144): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-24 22:10:53.325: E/AndroidRuntime(2144): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-24 22:10:53.325: E/AndroidRuntime(2144): at dalvik.system.NativeStart.main(Native Method)
08-24 22:10:53.325: E/AndroidRuntime(2144): Caused by: java.lang.NullPointerException
08-24 22:10:53.325: E/AndroidRuntime(2144): at ir.TeenStudio.ActivitiesManagement.Main.setLayoutTypoGraphy(Main.java:140)
08-24 22:10:53.325: E/AndroidRuntime(2144): at ir.TeenStudio.ActivitiesManagement.Main.onCreate(Main.java:91)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.Activity.performCreate(Activity.java:5231)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-24 22:10:53.325: E/AndroidRuntime(2144): ... 11 more
Any Idea? Help me plz to solve this

There is no Button with id = button_main_activity in your layout, so mainActivity field is null when you try to use it in setLayoutTypoGraphy method

Related

Force close by error java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

I am trying to use methods on my activity class to shorten my onCreate method.
But When I'm trying my app I got force close!
Activity Class (Main):
package ir.TeenStudio.ActivitiesManagement;
import java.util.ArrayList;
import java.util.HashMap;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.TextView;
public class Main extends Activity {
public static SQLiteDatabase ActivitiesListDatabase;
private SlidingMenu slidingMenu;
private ActivitiesExpandableListAdapter activitiesListViewAdapter;
private ArrayList<String> groupsList;
private HashMap<String, ArrayList<HashMap<String, String>>> childsList;
private ArrayList<HashMap<String,String>> todayChildsList;
private ArrayList<HashMap<String,String>> tomarrowChildsList;
private ArrayList<HashMap<String,String>> futureChildsList;
private ArrayList<HashMap<String,String>> oneDayChildsList;
private ExpandableListView mylist;
private TextView DayTextView;
private TextView MonthTextView;
private TextView YearTextView;
private Button MainActivity;
private Button ListActivity;
private Button Setting;
private Button Contact;
private Button Information;
private ImageButton Menu;
private ImageButton Add;
private Typeface Rezvan;
private Typeface DroidNaskh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
slidingMenu = new SlidingMenu(this);
activitiesListViewAdapter = new ActivitiesExpandableListAdapter(Main.this, groupsList, childsList);
groupsList = new ArrayList<String>();
childsList = new HashMap<String, ArrayList<HashMap<String,String>>>();
todayChildsList = new ArrayList<HashMap<String,String>>();
tomarrowChildsList = new ArrayList<HashMap<String,String>>();
futureChildsList = new ArrayList<HashMap<String,String>>();
oneDayChildsList = new ArrayList<HashMap<String,String>>();
mylist = (ExpandableListView) findViewById(R.id.activitiesListView);
DayTextView = (TextView) findViewById(R.id.day);
MonthTextView = (TextView) findViewById(R.id.month);
YearTextView = (TextView) findViewById(R.id.year);
MainActivity = (Button) findViewById(R.id.button_main_activity);
ListActivity = (Button) findViewById(R.id.button_lists_activity);
Setting = (Button) findViewById(R.id.button_setting);
Contact = (Button) findViewById(R.id.button_contact);
Information = (Button) findViewById(R.id.button_info);
Menu = (ImageButton) findViewById(R.id.menu_button);
Add = (ImageButton) findViewById(R.id.add_button);
Rezvan = Typeface.createFromAsset(getAssets(), "fonts/rezvan.ttf");
DroidNaskh = Typeface.createFromAsset(getAssets(), "fonts/droid_naskh.ttf");
// Sliding Menu
setSlidingMenu();
//TypoGraphy
setLayoutTypoGraphy();
//LayoutProgramming
setTime();
setButtonsEvent();
//Creating Database
try {
final String path = Environment.getDataDirectory() +"/data/" + getPackageName() + "/ActivitiesList.db";
ActivitiesListDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.CREATE_IF_NECESSARY);
String query ="CREATE TABLE IF NOT EXISTS Content(";
query += "Id INTEGER PRIMARY KEY AUTOINCREMENT,";
query += "Description TEXT,";
query += "AddLocation INTEGER,";
query += "Location TEXT,";
query += "AddDate INTEGER,";
query += "DateYear INTEGER,";
query += "DateMonth INTEGER,";
query += "DateDay INTEGER,";
query += "AddHour INTEGER,";
query += "Hour INTEGER,";
query += "Minutes INTEGER,";
query += "AddAlarm INTEGER,";
query += "AlarmTime INTEGER,";
query += "AddSpecial INTEGER)";
ActivitiesListDatabase.execSQL(query);
Log.d("Database", "Database Created");
} catch (Exception e) {
Log.e("Database", "Database Error");
}
//Receive Data From Database
receiveDataFromDatabase();
//Sending Data to ListView
mylist.setAdapter(activitiesListViewAdapter);
}
#Override
protected void onResume() {
super.onResume();
receiveDataFromDatabase();
activitiesListViewAdapter.notifyDataSetChanged();
}
public void setLayoutTypoGraphy() {
DayTextView.setTypeface(Rezvan);
MonthTextView.setTypeface(Rezvan);
YearTextView.setTypeface(Rezvan);
MainActivity.setTypeface(DroidNaskh);
ListActivity.setTypeface(DroidNaskh);
Setting.setTypeface(DroidNaskh);
Contact.setTypeface(DroidNaskh);
Information.setTypeface(DroidNaskh);
}
public void setTime() {
DayTextView.setText(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getDay());
YearTextView.setText(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getYear());
int solarMonth = Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getMonth());
switch (solarMonth) {
case 1:
MonthTextView.setText("فروردین");
break;
case 2:
MonthTextView.setText("اردیبهشت");
break;
case 3:
MonthTextView.setText("خرداد");
break;
case 4:
MonthTextView.setText("تیر");
break;
case 5:
MonthTextView.setText("مرداد");
break;
case 6:
MonthTextView.setText("شهریور");
break;
case 7:
MonthTextView.setText("مهر");
break;
case 8:
MonthTextView.setText("آبان");
break;
case 9:
MonthTextView.setText("آذر");
break;
case 10:
MonthTextView.setText("دی");
break;
case 11:
MonthTextView.setText("بهمن");
break;
case 12:
MonthTextView.setText("اسفند");
break;
}
}
public void receiveDataFromDatabase() {
groupsList.clear();
childsList.clear();
todayChildsList.clear();
tomarrowChildsList.clear();
futureChildsList.clear();
oneDayChildsList.clear();
groupsList.add("امروز");
groupsList.add("فردا");
groupsList.add("آینده");
groupsList.add("یه روز");
Cursor cr = ActivitiesListDatabase.rawQuery("SELECT * FROM Content", null);
if (cr.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Description", cr.getString(cr.getColumnIndex("Description")));
map.put("AddDate", cr.getString(cr.getColumnIndex("AddDate")));
map.put("AddLocation", cr.getString(cr.getColumnIndex("AddLocation")));
map.put("Location", cr.getString(cr.getColumnIndex("Location")));
map.put("DateYear", cr.getString(cr.getColumnIndex("DateYear")));
map.put("DateMonth", cr.getString(cr.getColumnIndex("DateMonth")));
map.put("DateDay", cr.getString(cr.getColumnIndex("DateDay")));
map.put("AddHour", cr.getString(cr.getColumnIndex("AddHour")));
map.put("Hour", cr.getString(cr.getColumnIndex("Hour")));
map.put("Minutes", cr.getString(cr.getColumnIndex("Minutes")));
map.put("AddAlarm", cr.getString(cr.getColumnIndex("AddAlarm")));
map.put("AlarmTime", cr.getString(cr.getColumnIndex("AlarmTime")));
map.put("AddSpecial", cr.getString(cr.getColumnIndex("AddSpecial")));
if (Integer.parseInt(cr.getString(cr.getColumnIndex("AddDate")))==1) {
if(Integer.parseInt(cr.getString(cr.getColumnIndex("DateYear")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getYear())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateMonth")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getMonth())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateDay")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getDay())){
todayChildsList.add(map);
}
else if (Integer.parseInt(cr.getString(cr.getColumnIndex("DateYear")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getYear())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateMonth")))==Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getMonth())
&&Integer.parseInt(cr.getString(cr.getColumnIndex("DateDay")))==(Integer.parseInt(ir.TeenStudio.ActivitiesManagement.ShamsiCalendar.getDay()))+1) {
tomarrowChildsList.add(map);
}
else {
futureChildsList.add(map);
}
} else oneDayChildsList.add(map);
} while (cr.moveToNext());
}
childsList.put(groupsList.get(0), todayChildsList);
childsList.put(groupsList.get(1), tomarrowChildsList);
childsList.put(groupsList.get(2), futureChildsList);
childsList.put(groupsList.get(3), oneDayChildsList);
}
public void setSlidingMenu() {
slidingMenu.setMode(SlidingMenu.RIGHT);
slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
slidingMenu.setShadowDrawable(R.drawable.menu_shadow);
slidingMenu.setShadowWidth(30);
slidingMenu.setFadeDegree(1.0f);
slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
DisplayMetrics display = this.getResources().getDisplayMetrics();
int width = display.widthPixels;
int menu_width = width - width / 3;
if (menu_width < 100) {
menu_width = 100;
}
slidingMenu.setBehindWidth(menu_width);
slidingMenu.setMenu(R.layout.main_right);
}
public void setButtonsEvent() {
OnClickListener ButtonsEvents = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.menu_button:
slidingMenu.toggle();
break;
case R.id.add_button:
Intent popUpAddItemDialogActivity = new Intent(Main.this, AddItem.class);
startActivity(popUpAddItemDialogActivity);
break;
case R.id.button_main_activity:
//Start main activity
break;
case R.id.button_lists_activity:
//Start lists activity
break;
case R.id.button_setting:
//Start setting
break;
case R.id.button_contact:
//Start contact activity
break;
case R.id.button_info:
//Start info activity
break;
default:
break;
}
}
};
Menu.setOnClickListener(ButtonsEvents);
Add.setOnClickListener(ButtonsEvents);
}
}
And this is my Manifest Code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.TeenStudio.ActivitiesManagement"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/name_application"
android:theme="#style/AppTheme" >
<activity
android:name="ir.TeenStudio.ActivitiesManagement.Splash"
android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="ir.TeenStudio.ActivitiesManagement.Main" android:theme="#android:style/Theme.Light.NoTitleBar.Fullscreen">
</activity>
<activity android:theme="#android:style/Theme.Dialog" android:name="AddItem"></activity>
</application>
</manifest>
Log
08-24 22:10:53.325: E/AndroidRuntime(2144): FATAL EXCEPTION: main
08-24 22:10:53.325: E/AndroidRuntime(2144): Process: ir.TeenStudio.ActivitiesManagement, PID: 2144
08-24 22:10:53.325: E/AndroidRuntime(2144): java.lang.RuntimeException: Unable to start activity ComponentInfo{ir.TeenStudio.ActivitiesManagement/ir.TeenStudio.ActivitiesManagement.Main}: java.lang.NullPointerException
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.os.Handler.dispatchMessage(Handler.java:102)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.os.Looper.loop(Looper.java:136)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-24 22:10:53.325: E/AndroidRuntime(2144): at java.lang.reflect.Method.invokeNative(Native Method)
08-24 22:10:53.325: E/AndroidRuntime(2144): at java.lang.reflect.Method.invoke(Method.java:515)
08-24 22:10:53.325: E/AndroidRuntime(2144): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-24 22:10:53.325: E/AndroidRuntime(2144): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-24 22:10:53.325: E/AndroidRuntime(2144): at dalvik.system.NativeStart.main(Native Method)
08-24 22:10:53.325: E/AndroidRuntime(2144): Caused by: java.lang.NullPointerException
08-24 22:10:53.325: E/AndroidRuntime(2144): at ir.TeenStudio.ActivitiesManagement.Main.setLayoutTypoGraphy(Main.java:140)
08-24 22:10:53.325: E/AndroidRuntime(2144): at ir.TeenStudio.ActivitiesManagement.Main.onCreate(Main.java:91)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.Activity.performCreate(Activity.java:5231)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-24 22:10:53.325: E/AndroidRuntime(2144): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-24 22:10:53.325: E/AndroidRuntime(2144): ... 11 more
Any Idea to solve this problem?
Force close was caused by the getAssets() call outside activity methods.So intialize Typeface i.e. getAssets() in onCreate method,So change
//Typography
Typeface Rezvan = Typeface.createFromAsset(getAssets(), "fonts/rezvan.ttf");
Typeface DroidNaskh = Typeface.createFromAsset(getAssets(), "fonts/droid_naskh.ttf");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
to
Typeface Rezvan,DroidNaskh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Typography
Rezvan = Typeface.createFromAsset(getAssets(), "fonts/rezvan.ttf");
DroidNaskh = Typeface.createFromAsset(getAssets(), "fonts/droid_naskh.ttf");

public static hashmap clear and put not work properly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
At first I click the “mn_column” button, then works properly. But I go back and click again “mn_column” or “mn_blog” then it show flowing error :
08-10 02:30:16.441: E/AndroidRuntime(1098): FATAL EXCEPTION: main
08-10 02:30:16.441: E/AndroidRuntime(1098): Process: com.sams.main.news, PID: 1098
08-10 02:30:16.441: E/AndroidRuntime(1098): java.lang.NullPointerException
08-10 02:30:16.441: E/AndroidRuntime(1098): at com.sams.main.news.MainNewsActivity$6.onClick(MainNewsActivity.java:539)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.view.View.performClick(View.java:4438)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.view.View$PerformClick.run(View.java:18422)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.os.Handler.handleCallback(Handler.java:733)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.os.Handler.dispatchMessage(Handler.java:95)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.os.Looper.loop(Looper.java:136)
08-10 02:30:16.441: E/AndroidRuntime(1098): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-10 02:30:16.441: E/AndroidRuntime(1098): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 02:30:16.441: E/AndroidRuntime(1098): at java.lang.reflect.Method.invoke(Method.java:515)
08-10 02:30:16.441: E/AndroidRuntime(1098): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-10 02:30:16.441: E/AndroidRuntime(1098): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-10 02:30:16.441: E/AndroidRuntime(1098): at dalvik.system.NativeStart.main(Native Method)
Picture:
Code:
MainNewsActivity.java
public class MainNewsActivity extends TabActivity {
String menuLink;
int menuKey;
private List<RssItem> menuItems = new ArrayList<RssItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button mnColumn = (Button) layout.findViewById(R.id.mn_column);
mnColumn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
menuKey = 0;
//Varialbes.menuNewsMap.clear();
menuLink = "http://www.aaa.org/rss/rssblog";
menuItems = pareser.getNewsList(menuLink);
Varialbes.menuNewsMap.put(menuKey, menuItems);
Intent intent = new Intent(MainNewsActivity.this,MenuNewsActivity.class);
intent.putExtra(Varialbes.PAPER, paper);
intent.putExtra(Varialbes.MENU_TITLE, "Column");
intent.putExtra(Varialbes.MENU_KEY, menuKey);
startActivity(intent);
}
});
Button mnBlog = (Button) layout.findViewById(R.id.mn_blog);
mnBlog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
menuKey = 1;
menuLink = "http://www.bbb.org/rss/rssblog";
menuItems = pareser.getNewsList(menuLink);
Varialbes.menuNewsMap.put(menuKey, menuItems);
Intent intent = new Intent(MainNewsActivity.this,MenuNewsActivity.class);
intent.putExtra(Varialbes.PAPER, paper);
intent.putExtra(Varialbes.MENU_TITLE, "Blog");
intent.putExtra(Varialbes.MENU_KEY, menuKey);
startActivity(intent);
}
});
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/popup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#DEE4DF"
android:orientation="vertical" >
<Button
android:id="#+id/mn_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2.98"
android:background="#drawable/menu_selector"
android:gravity="left|center_vertical|center_horizontal"
android:text="Column" />
<Button
android:id="#+id/mn_blog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2.98"
android:background="#drawable/menu_selector"
android:gravity="left|center_vertical|center_horizontal"
android:text="Blog" />
</LinearLayout>
Varialbes.java
public class Varialbes {
public static final String PAPER = "paper";
public static final String MENU_TITLE = "title";
public static final String MENU_KEY = "menu_key";
public static HashMap<Integer, List<RssItem>> menuNewsMap = new HashMap<Integer, List<RssItem>>();
}
MenuNewsActivity.java
public class MenuNewsActivity extends Activity {
private ListView listNews;
private List<RssItem> items;
private Button backButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_news);
// ..........................Back..........................
backButton = (Button) findViewById(R.id.back_button);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent backIntent = new Intent(MenuNewsActivity.this,
MainNewsActivity.class);
finish();
startActivity(backIntent);
}
});
// ................................................
listNews = (ListView) findViewById(R.id.newsList);
Bundle bundle = getIntent().getExtras();
int paper = bundle.getInt(Varialbes.PAPER);
TextView tv = (TextView) findViewById(R.id.hedderText);
String menutitle = bundle.getString(Varialbes.MENU_TITLE);
int menuKey = bundle.getInt(Varialbes.MENU_KEY);
tv.setText(menutitle);
items = Varialbes.menuNewsMap.get(menuKey);
MenuNewsAdater adapter = new MenuNewsAdater(this,
Varialbes.ICONS[paper], items);
listNews.setAdapter(adapter);
}
}
Please help me.
You pareser variable does not properly. So you
add flowing code:
RssParser pareser= new RssParser();
Try this way:
public void onClick(View v) {
menuKey = 0;
Varialbes.menuNewsMap.clear();
menuLink = "http://www.aaa.org/rss/rssblog";
RssParser pareser= new RssParser();
menuItems = pareser.getNewsList(menuLink);
Varialbes.menuNewsMap.put(menuKey, menuItems);
Intent intent = new Intent(MainNewsActivity.this,MenuNewsActivity.class);
intent.putExtra(Varialbes.PAPER, paper);
intent.putExtra(Varialbes.MENU_TITLE, "Column");
intent.putExtra(Varialbes.MENU_KEY, menuKey);
startActivity(intent);
}

My Android app crashes when trying to store SQLite data

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.

Can't display banners

I have this activity - including the needed code in order to load the admob banner ads.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.gs.britishjokes.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AllJokes extends Activity {
public static ArrayAdapter<String> adapter;
public static ListView listView;
private AdView adView;
/* Your ad unit id. Replace with your actual ad unit id. */
private static final String AD_UNIT_ID = "ca-app-pub-codehere/code";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_jokes);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
// .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
.build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
final GlobalsHolder globals = (GlobalsHolder)getApplication();
// if(globals.isLoaded == false){ SETJOKESNAMELIST MAI SE POLZVA OT DRUGO ACTIVITY!!!! ZATOVA IZLIZA PRAZNO SLED PROVERKATA!
new loadJson().execute();
// }
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
adapter.clear();
adapter.addAll(globals.getMyStringArray());
listView = (ListView) findViewById(R.id.allJokesList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
globals.setClickedJokeName((String) ((TextView) view).getText());
openJokeBody(view);
globals.setClickedPosition(position);
// When clicked, shows a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.all_jokes, menu);
return true;
}
public class loadJson extends AsyncTask<Void, Integer, String[]>{
private ProgressDialog Dialog = new ProgressDialog(AllJokes.this);
#Override
protected void onPreExecute()
{
Dialog.setMessage("Fetching the latest jokes!");
Dialog.show();
}
#Override
protected String[] doInBackground(Void... params) {
/*Getting the joke names JSON string response from the server*/
URL u;
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
try {
u = new URL("https://site.com/android/Jokes/showJokes.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
try {
u = new URL("https://site.com/android/Jokes/showJokesBody.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer2.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
// return buffer.toString(); ako se naloji da vurna - da pogledna tva return4e
return new String[]{buffer.toString(), buffer2.toString()};
}
#SuppressLint("NewApi")
protected void onPostExecute(String[] buffer) {
final GlobalsHolder globals = (GlobalsHolder)getApplication();
JSONArray jsonArray = new JSONArray();
JSONArray jsonArray1 = new JSONArray();
try {
jsonArray = new JSONArray(buffer[0]);
jsonArray1 = new JSONArray(buffer[1]);
} catch (JSONException e) {
e.printStackTrace();
}
/*Looping trough the results and adding them to a list*/
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list1 = new ArrayList<String>();
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
try {
list.add(jsonArray.get(i).toString());
globals.setJokeNamesList(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if (jsonArray != null) {
int len = jsonArray1.length();
for (int i=0;i<len;i++){
try {
list1.add(jsonArray1.get(i).toString());
globals.setList(list1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/* Redrwawing the view */
adapter.clear();
adapter.addAll(list);
Dialog.dismiss();
globals.setLoaded(true);
}
}
/*This method opens the new activity - TopJokesBody when a joke name from the list is clicked*/
public void openJokeBody(View view) {
Intent intent = new Intent(this, AllJokesBody.class);
startActivity(intent);
}
}
It is my 1st try and I already stucked. Logcat is throwing tons of exceptions and to be honest I can't understand what I'm doing wrong.
Here the exceptions are:
03-29 13:55:37.713: E/AndroidRuntime(1750): FATAL EXCEPTION: main
03-29 13:55:37.713: E/AndroidRuntime(1750): Process: com.gs.britishjokes, PID: 1750
03-29 13:55:37.713: E/AndroidRuntime(1750): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gs.britishjokes/com.gelasoft.britishjokes.AllJokes}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Handler.dispatchMessage(Handler.java:102)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Looper.loop(Looper.java:136)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invokeNative(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invoke(Method.java:515)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-29 13:55:37.713: E/AndroidRuntime(1750): at dalvik.system.NativeStart.main(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.widget.AdapterView.addView(AdapterView.java:452)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.gelasoft.britishjokes.AllJokes.onCreate(AllJokes.java:55)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Activity.performCreate(Activity.java:5231)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-29 13:55:37.713: E/AndroidRuntime(1750): ... 11 more
I'm sure that I miss something inside of the xml layout file, but I'm not able to spot it as a total beginner.
Ps. here the layout is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".AllJokes" >
<ListView
android:id="#+id/allJokesList"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</RelativeLayout>
Should I declare something in it? Please, give me a clue!
Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
you cant add a view to adapterview
your issue is with
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
You need to add the adView inside the adapter
http://googleadsdeveloper.blogspot.co.il/2012/03/embedding-admob-ads-within-listview-on.html
Don't try to add an AdView as an element in a ListView. It is a recipe for pain as it will be entirely different to your other items with different needs.
Add it as it's own element either above or below your ListView.
Instead create a LinearLayout either above or below your ListView
<LinearLayout android:id="#+id/adViewContainer
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
and then change this part of your onCreate to
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
final ViewGroup adViewContainer = (ViewGroup) findViewById(R.id.adViewContainer);
adViewContainer.addView(adView);

nullpointerexception cannot start activity

I keep getting nullpointerexception errors when I try to start a second activity from my main activity, my main activity code goes as such:
package com.cep.daredevil;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public boolean filled = true;
EditText taskArray[] = new EditText[200];
EditText descArray[] = new EditText[200];
String taskArr[] = new String[200];
String descArr[] = new String[200];
int taskId[] = new int[200];
int descId[] = new int[200];
int n=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout llayout = (LinearLayout)findViewById(R.id.llayout);
Button addfield = new Button(this);
addfield.setText("+");
llayout.addView(addfield);
addfield.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
addtask();
}
});
for(int i=0;i<3;i++)
{
addtask();
}
LinearLayout blayout = (LinearLayout)findViewById(R.id.blayout);
Button submit = new Button(this);
submit.setText("Enter Dare");
Button viewdare = new Button(this);
viewdare.setText("View Dares");
blayout.addView(submit);
blayout.addView(viewdare);
submit.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
inputdare(null);
}
});
viewdare.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
listdare();
}
});
}
#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;
}
public void addtask()
{
LinearLayout llayout = (LinearLayout)findViewById(R.id.llayout);
taskArray[n] = new EditText(this);
taskArray[n].setHint("Task Title");
taskArray[n].setId(n+10000000);
taskArray[n].setPadding(26,30,25,8);
descArray[n] = new EditText(this);
descArray[n].setHint("Task Description");
descArray[n].setId(n+20000000);
llayout.addView(taskArray[n]);
llayout.addView(descArray[n]);
n++;
}
public void inputdare(View v){
EditText daretitle = (EditText)findViewById(R.id.title);
String dare = daretitle.getText().toString();
for (int i=0;i<n;i++)
{
if (taskArr[i] != null)
{
taskArr[i] = taskArray[i].getText().toString();
}
Integer id = taskArray[i].getId();
if (id != null)
{
taskId[i] = id;
}
}
Intent intent = new Intent(this, DisplayDares.class);
Bundle bundle = new Bundle();
bundle.putStringArray("TASKS", taskArr);
bundle.putIntArray("TASKID", taskId);
bundle.putBoolean("INPUT", true);
intent.putExtras(bundle);
startActivity(intent);
}
}
public void listdare()
{
Intent intent = new Intent(this, DisplayDares.class);
Bundle bundle = new Bundle();
bundle.putBoolean("INPUT", false);
intent.putExtras(bundle);
startActivity(intent);
}
}
the function that seems to be causing the problem is in my second activity, over here:
package com.cep.daredevil;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DisplayDares extends Activity {
public final static String PREFS = "Preferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_dare);
setupActionBar();
Bundle bundle = getIntent().getExtras();
Boolean input = bundle.getBoolean("INPUT");
if (input == false){}
else
{
int[] taskId = bundle.getIntArray("TASKID");
final String[] taskArray = bundle.getStringArray("TASKS");
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
TextView test = (TextView)findViewById(taskId[0]);
test.setText(taskArray[1]);
layout.addView(test);
}
}
}
the error I get is this:
03-08 13:32:18.053: E/AndroidRuntime(6873): FATAL EXCEPTION: main
03-08 13:32:18.053: E/AndroidRuntime(6873): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cep.daredevil/com.cep.daredevil.DisplayDares}: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.os.Looper.loop(Looper.java:137)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-08 13:32:18.053: E/AndroidRuntime(6873): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 13:32:18.053: E/AndroidRuntime(6873): at java.lang.reflect.Method.invoke(Method.java:511)
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-08 13:32:18.053: E/AndroidRuntime(6873): at dalvik.system.NativeStart.main(Native Method)
03-08 13:32:18.053: E/AndroidRuntime(6873): Caused by: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.cep.daredevil.DisplayDares.onCreate(DisplayDares.java:32)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.Activity.performCreate(Activity.java:5104)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-08 13:32:18.053: E/AndroidRuntime(6873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
After pasing your code it seems line 34 is:
layout.addView(test);
So this line generates a nullpointer exception
Check if the id of your layout is the same.
Tip:
Further in your error stacktrace you can see what causes the error:
03-08 13:32:18.053: E/AndroidRuntime(6873): Caused by: java.lang.NullPointerException
03-08 13:32:18.053: E/AndroidRuntime(6873): at com.cep.daredevil.DisplayDares.onCreate(DisplayDares.java:34)
DisplayDares.java:34
Means line 34 in your DisplayDares.java file.
You will see it is the following line:
layout.addView(test);
Now test cannot be NULL because it wouldn't have thrown that error. So layout must be.

Categories

Resources