nullpointerexception cannot start activity - java

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.

Related

Unable to start Activity Componentinfo (Adapter Constructor)

I tried to create a simple listview. I've done it many times & this is the first time i face such errors. Tried this in both Eclipse Luna & indigo. Both have the same error.
Here is where i create an instant of the adapter :
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class ActivityMain extends Activity {
public ArrayList<StructRemedy> remedies = new ArrayList<StructRemedy>();
private ListView lstContent;
public AdapterRemedy adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstContent = (ListView) findViewById(R.id.lstContent);
adapter = new AdapterRemedy(remedies);
randomPopulation();
lstContent.setAdapter(adapter);
}
private void randomPopulation() {
for (int i = 0; i < 30; i++) {
StructRemedy remedy = new StructRemedy();
remedy.title = "Remedy" + i;
remedy.description = "Desc" + i;
remedy.rateValue = (float) (Math.random() * 5);
remedy.type = "tisane";
remedy.use = "Headaches";
remedies.add(remedy);
}
adapter.notifyDataSetChanged();
}
}
Now the error log (The error referes to the line where i create the constructor , u know the "super" line) :
06-08 10:03:27.875: E/AndroidRuntime(2715): FATAL EXCEPTION: main
06-08 10:03:27.875: E/AndroidRuntime(2715): java.lang.RuntimeException: Unable to start activity ComponentInfo{ahmad.azimi.app.herbal_remedies/test.test1.app.herbal_remedies.ActivityMain}: java.lang.NullPointerException
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.os.Handler.dispatchMessage(Handler.java:99)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.os.Looper.loop(Looper.java:137)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-08 10:03:27.875: E/AndroidRuntime(2715): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 10:03:27.875: E/AndroidRuntime(2715): at java.lang.reflect.Method.invoke(Method.java:511)
06-08 10:03:27.875: E/AndroidRuntime(2715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-08 10:03:27.875: E/AndroidRuntime(2715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-08 10:03:27.875: E/AndroidRuntime(2715): at dalvik.system.NativeStart.main(Native Method)
06-08 10:03:27.875: E/AndroidRuntime(2715): Caused by: java.lang.NullPointerException
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)
06-08 10:03:27.875: E/AndroidRuntime(2715): at test.test1.app.herbal_remedies.AdapterRemedy.<init>(AdapterRemedy.java:22)
06-08 10:03:27.875: E/AndroidRuntime(2715): at test.test1.app.herbal_remedies.ActivityMain.onCreate(ActivityMain.java:22)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.Activity.performCreate(Activity.java:5104)
06-08 10:03:27.875: E/AndroidRuntime(2715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-08 10:03:27.875: E/AndroidRuntime(2715): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
This is the adapter :
import java.util.ArrayList;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
public class AdapterRemedy extends ArrayAdapter<StructRemedy> {
public AdapterRemedy(ArrayList<StructRemedy> remedies) {
super(G.context, R.layout.adapter_notes, remedies);
}
private static class ViewHolder {
public TextView txtTitle;
public TextView txtType;
public TextView txtFor;
public RatingBar rating;
public ViewGroup layoutRoot;
public ImageView imgLogo;
public ViewHolder(View view) {
layoutRoot = (ViewGroup) view.findViewById(R.id.layoutRoot);
txtTitle = (TextView) view.findViewById(R.id.txtTitle);
txtType = (TextView) view.findViewById(R.id.txtType);
txtFor = (TextView) view.findViewById(R.id.txtFor);
rating = (RatingBar) view.findViewById(R.id.rate);
imgLogo = (ImageView) view.findViewById(R.id.imgLogo);
}
public void fill(final ArrayAdapter<StructRemedy> adapter, final StructRemedy item, final int position) {
txtTitle.setText(item.title);
txtType.setText(item.type);
txtFor.setText(item.use);
rating.setRating(item.rateValue);
//imgLogo.setImageBitmap(bm);
layoutRoot.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(G.currentActivity, ActivitySelect.class);
intent.putExtra("POSITION", position);
G.currentActivity.startActivity(intent);
}
});
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
StructRemedy item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.adapter_notes, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}
}
Try this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstContent = (ListView) findViewById(R.id.lstContent);
randomPopulation();
}
Put adapter = new AdapterRemedy (remedies ) ; after randomPopulation. Or set adapter in randomPopulation method.
And remove adapter.notifyDataSetchanged() from randomPopulation.
Do some changes in your adapter code :
public AdapterRemedy(ArrayList<StructRemedy> remedies) {
super(G.context, R.layout.adapter_notes, remedies);
}
Change it to this :
public AdapterRemedy(context,ArrayList<StructRemedy> remedies) {
super(context, R.layout.adapter_notes, remedies);
}
And in randomPopulation :
adapter = new AdapterRemedy(this,remedies);
lstContent.setAdapter(adapter);
adapter.notifyDataSetChanged();
Change your onCreate() like ,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstContent = (ListView) findViewById(R.id.lstContent);
randomPopulation();
adapter = new AdapterRemedy(remedies);
lstContent.setAdapter(adapter);
}
Call randomPopulation() before the adater Initialization. remove
adapter.notifyDataSetChanged();

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");

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

Null Pointer Exception in string

I am getting a null pointer exception in my code.Please help me to solve it .
Here is my code.
package com.example.game;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class GuessActivity extends ListActivity implements OnClickListener
{
EditText GNum;
Button nxt;
int[] a = new int[4];
int[] d = new int[4];
int[] b = {0,0,0,0,0,0,0,0};
int[] c = {0,0,0,0,0,0,0,0};
int[] x = new int[8];
int t = 0;
String [] gN = new String[8];
String [] gB = new String[8];
String [] gC = new String[8];
ListAdapter adapter;
/*ArrayList<HashMap<String, String>> output = new ArrayList<HashMap<String, String>>();
HashMap<String, String> out = new HashMap<String, String>();*/
//String KEY_NUM = "1" , KEY_BULLS="2" , KEY_COWS="3";
private class list
{
TextView guess;
TextView bulls;
TextView cows;
}
list lv = null;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.guess_activity);
GNum = (EditText) findViewById(R.id.etGuessNum);
nxt = (Button) findViewById(R.id.btNxt);
int y = getIntent().getExtras().getInt("num");
for(int i=0;i<4;i++)
{
a[i] = y%10;
y = y/10;
}
/*adapter = new SimpleAdapter(this,output,R.layout.list_item,
new String[]{KEY_NUM , KEY_BULLS , KEY_COWS},new int[]{
R.id.tvGuessNum , R.id.tvBulls , R.id.tvCows});*/
nxt.setOnClickListener(this);
GNum.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
if(v.getId() == R.id.btNxt)
{
t++;
if(t>8)
{
Toast.makeText(getApplicationContext(), "You Lost the Game",
Toast.LENGTH_SHORT).show();
return;
}
else
{
gN[t-1] = GNum.getText().toString();
int l = gN[t-1].length();
if(l!=4)
{
Toast.makeText(getApplicationContext(),"Number should be of 4 digits",
Toast.LENGTH_LONG).show();
return;
}
else
{
x[t-1] = Integer.parseInt(gN[t-1]);
for(int i=0;i<4;i++)
{
d[i] = x[t-1]%10;
x[t-1] = x[t-1]/10;
}
if(d[0] == a[0])
b[t-1]++;
if(d[0] == a[1] || d[0] == a[2] || d[0] == a[3])
c[t-1]++;
if(d[1] == a[1])
b[t-1]++;
if(d[1] == a[0] || d[1] == a[2] || d[1] == a[3])
c[t-1]++;
if(d[2] == a[2])
b[t-1]++;
if(d[2] == a[1] || d[2] == a[0] || d[2] == a[3])
c[t-1]++;
if(d[3] == a[3])
b[t-1]++;
if(d[3] == a[1] || d[3] == a[2] || d[3] == a[0])
c[t-1]++;
if(b[t-1] == 4)
{
Toast.makeText(getApplicationContext(), "You Win",
Toast.LENGTH_SHORT).show();
return;
}
gB[t-1] = Integer.toString(b[t-1]);
gC[t-1] = Integer.toString(c[t-1]);
lv = new list();
lv.guess = (TextView) findViewById(R.id.tvGuessNum);
lv.bulls = (TextView) findViewById(R.id.tvBulls);
lv.cows = (TextView) findViewById(R.id.tvCows);
lv.guess.setText(gN[t-1]);
lv.bulls.setText(gB[t-1]);
lv.cows.setText(gC[t-1]);
/*out.put(KEY_NUM, gN[t-1]);
out.put(KEY_BULLS ,String.valueOf(b[t-1]));
out.put(KEY_COWS , String.valueOf(c[t-1]));
output.add(t-1 , out);
setListAdapter(adapter);*/
}
}
}
else if(v.getId()==R.id.etGuessNum)
{
GNum.setText("");
}
}
}
Here is my log cat.
03-08 02:58:55.760: E/AndroidRuntime(861): FATAL EXCEPTION: main
03-08 02:58:55.760: E/AndroidRuntime(861): Process: com.example.game, PID: 861
03-08 02:58:55.760: E/AndroidRuntime(861): java.lang.NullPointerException
03-08 02:58:55.760: E/AndroidRuntime(861): at com.example.game.GuessActivity.onClick(GuessActivity.java:138)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.view.View.performClick(View.java:4438)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.view.View$PerformClick.run(View.java:18422)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.os.Handler.handleCallback(Handler.java:733)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.os.Handler.dispatchMessage(Handler.java:95)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.os.Looper.loop(Looper.java:136)
03-08 02:58:55.760: E/AndroidRuntime(861): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-08 02:58:55.760: E/AndroidRuntime(861): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 02:58:55.760: E/AndroidRuntime(861): at java.lang.reflect.Method.invoke(Method.java:515)
03-08 02:58:55.760: E/AndroidRuntime(861): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-08 02:58:55.760: E/AndroidRuntime(861): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-08 02:58:55.760: E/AndroidRuntime(861): at dalvik.system.NativeStart.main(Native Method)
line 138 is in on click method -> if -> else ->else ->lv.bulls.setText(gB[t-1];
Probably because you haven't instantiated lv anywhere. It's initialized as null in the beginning and the same value is used at line 138.
Probably your lv.bulls is null. Please make sure you have TextView with id = tvBulls (case-sensitive) at your layout.

Android custom listview click - How to call an intent without crashing?

All right, so I've been a few hours on this, and can't get it to work.
Basically, I wanna call an intent from a clickable listview. I'm displaying car models and it's code on a list, when you click, you're supposed to be taken to another screen to edit the car's properties, however, I'm beggining to think it's impossible
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, arrayListCarros);
mainListView.setAdapter( listAdapter );
db.close();
mainListView.setClickable(true);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent i = new Intent(listagemcarro.this,com.example.trabalhosql.edicao.class);
startActivity(i);
}
});
The rest of the code:
public class listagemcarro extends Activity {
Button buttonCadastro;
Button buttonListagem;
Button buttonBusca;
Button button1;
Intent itListagem = new Intent();
Intent itCadastro = new Intent();
Intent itBusca = new Intent();
//Intent itEdicao = new Intent();
Intent itEdicao2 = new Intent();
String id="";
public SQLiteDatabase db;
public String BANCO = "banco.db";
public String TABELA = "carro";
int posicao=123123;
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
public void toast(int position){
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, position, Toast.LENGTH_SHORT);
toast.show();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listagemcarro);
Intent itRecebeParametros = getIntent();
if(itRecebeParametros != null){
id = itRecebeParametros.getStringExtra("id");
}
db = openOrCreateDatabase(BANCO, Context.MODE_PRIVATE, null);
Cursor linhas = db.query(TABELA, new String[] {"ID_PESSOA, MODELO"},"id_pessoa = '"+id+"'", null, null, null, null);
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayList <String>arrayListCarros = new ArrayList<String> ();
if(linhas.moveToFirst()){
do{
arrayListCarros.add(linhas.getString(0) +" " + linhas.getString(1));
}
while(linhas.moveToNext());
}
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, arrayListCarros);
mainListView.setAdapter( listAdapter );
db.close();
mainListView.setClickable(true);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent i = new Intent(listagemcarro.this,com.example.trabalhosql.edicao.class);
startActivity(i);
}
});
}
error
11-19 23:18:09.136: W/dalvikvm(1784): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
11-19 23:18:09.136: E/AndroidRuntime(1784): Uncaught handler: thread main exiting due to uncaught exception
11-19 23:18:09.147: E/AndroidRuntime(1784): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trabalhosql/com.example.trabalhosql.edicao}: java.lang.NullPointerException
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.os.Handler.dispatchMessage(Handler.java:99)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.os.Looper.loop(Looper.java:123)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.main(ActivityThread.java:4363)
11-19 23:18:09.147: E/AndroidRuntime(1784): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 23:18:09.147: E/AndroidRuntime(1784): at java.lang.reflect.Method.invoke(Method.java:521)
11-19 23:18:09.147: E/AndroidRuntime(1784): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
11-19 23:18:09.147: E/AndroidRuntime(1784): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-19 23:18:09.147: E/AndroidRuntime(1784): at dalvik.system.NativeStart.main(Native Method)
11-19 23:18:09.147: E/AndroidRuntime(1784): Caused by: java.lang.NullPointerException
11-19 23:18:09.147: E/AndroidRuntime(1784): at com.example.trabalhosql.edicao.onCreate(edicao.java:42)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-19 23:18:09.147: E/AndroidRuntime(1784): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
11-19 23:18:09.147: E/AndroidRuntime(1784): ... 11 more
edicao.class
package com.example.trabalhosql;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class edicao extends Activity {
String id="";
String modeloCarro = "";
TextView textViewCarroEscolhido;
public SQLiteDatabase db;
public String BANCO = "banco.db";
public String TABELA = "carro";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listagemcarro);
Intent itRecebeParametros = getIntent();
if(itRecebeParametros != null){
id = itRecebeParametros.getStringExtra("id");
modeloCarro = itRecebeParametros.getStringExtra("modeloCarro");
}
textViewCarroEscolhido = (TextView) findViewById(R.id.textViewCarroEscolhido);
textViewCarroEscolhido.setText(modeloCarro);
}
}
EDIT
I'm guessing that this part of the edicao class is incorrect:
setContentView(R.layout.listagemcarro);
That itself might not have thrown the error, but trying to finding views (like your textView) in it that don't exist would.
textViewCarroEscolhido is null. Make sure that it exists in listagemcarro.xml
In case anyone comes here for calling intents in drawing situations such as canvas. Ensure you are not calling the intent multiple times. In my situation the invalidate() method kept getting called and made many intent calls. Ensure to use some sort of flip mechanism to stop invalidate() from being called. Will work like a charm.

Categories

Resources