This is my code:
Line no. 94 corresponds to my method of getting all ids.
Always I get an error : Your application has stopped unexpectedly.
package karan.app.caloriecalculator;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class Main extends Activity implements AdapterView.OnItemSelectedListener {
Button bcal;
TextView intro, choose, duration, min, weight, kg;
EditText dur, weigh;
Spinner sel;
String temp;
public double w, d, calories;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
get_all_ids();
setArrayAdapter();
sel.setOnItemSelectedListener(this);
bcal.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
w = Float.valueOf(weigh.getText().toString());
d = Float.valueOf(dur.getText().toString());
if (temp.contentEquals("Aerobics:general")){
calories = 0.11*w*d;
}
else if (temp.contentEquals("Badminton")){
calories = (w/13)*d;
}
else if (temp.contentEquals("Basketball")){
calories = (w/7.45)*d;
}
else if (temp.contentEquals("Bicycling:slow (10-12 mph)")){
calories = (w/9.65)*d;
}
else if (temp.contentEquals("Bicycling:general (12-14 mph)")){
calories = (w/7.2)*d;
}
else if (temp.contentEquals("Bicycling:moderate (14-16 mph)")){
calories = (w/6)*d;
}
else if (temp.contentEquals("Bicycling:fast (16+ mph)")){
calories = (w/5)*d;
}
else if (temp.contentEquals("Bowling")){
calories = (w/19.1)*d;
}
else if (temp.contentEquals("Boxing: punching bag")){
calories = (w/9.6)*d;
}
else if (temp.contentEquals("Boxing: sparring")){
calories = (w/6.375)*d;
}
/* Thread t = new Thread(){
public void run(){
try{
sleep(1);
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openResult = new Intent("karan.app.caloriecalculator.RESULT");
startActivity(openResult);
}
}
}; // close the thread with a ;
*/
}});
}
public void get_all_ids() {
bcal.findViewById(R.id.b1);
intro.findViewById(R.id.tv1);
choose.findViewById(R.id.tv2);
duration.findViewById(R.id.tv3);
min.findViewById(R.id.tv4);
weight.findViewById(R.id.tv5);
kg.findViewById(R.id.tv6);
dur.findViewById(R.id.et2);
weigh.findViewById(R.id.et1);
sel.findViewById(R.id.sp1);
}
public double getCalories() {
return calories;
}
public void setArrayAdapter(){
//The createFromResource() method allows you to create an ArrayAdapter from the string array
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.choices, android.R.layout.simple_spinner_dropdown_item);
//You should then call setDropDownViewResource(int) to specify the layout the adapter should use to display the list of spinner choices
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Call setAdapter() to apply the adapter to your Spinner.
sel.setAdapter(adapter);
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Object item = parent.getItemAtPosition(position);
temp = item.toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
LogCat:
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.os.Handler.dispatchMessage(Handler.java:99)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.os.Looper.loop(Looper.java:123)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-28 14:10:03.545: E/AndroidRuntime(266): at java.lang.reflect.Method.invokeNative(Native Method)
07-28 14:10:03.545: E/AndroidRuntime(266): at java.lang.reflect.Method.invoke(Method.java:521)
07-28 14:10:03.545: E/AndroidRuntime(266): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-28 14:10:03.545: E/AndroidRuntime(266): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-28 14:10:03.545: E/AndroidRuntime(266): at dalvik.system.NativeStart.main(Native Method)
07-28 14:10:03.545: E/AndroidRuntime(266): Caused by: java.lang.NullPointerException
07-28 14:10:03.545: E/AndroidRuntime(266): at karan.app.caloriecalc.MainActivity.get_all_ids(MainActivity.java:96)
07-28 14:10:03.545: E/AndroidRuntime(266): at karan.app.caloriecalc.MainActivity.onCreate(MainActivity.java:28)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-28 14:10:03.545: E/AndroidRuntime(266): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-28 14:10:03.545: E/AndroidRuntime(266): ... 11 more
You are incorrectly fetching views in get_all_ids().
To get a view, you must do:
TextView intro;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intro = (TextView) findViewById(R.id.tv1);
....
}
// You can now use intro and methods of TextView class.
I recommend you read the Android Beginner Guides.
Related
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();
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);
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.
I'm pretty new to Java and Android. I'm trying to make an app that calculates a volume of a liquid in a cylinder, then return the result to a textView box. But now when I click the button to Calculate, it is crashing and I don't know what I'm missing. Everything compiles fine.
package com.somename.fuel.volume.calculator;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
public class CalculateCylinder extends Activity {
EditText length, width, height, depth;
TextView result;
Button calculate;
double firstNum, secNum, thirdNum, volume, area;
double liqVolume;
double radius;
double a, l, aSide,aTop,b,Arc,FluidSurfaceAreaTotal,r,d,v,h,fsal;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculate_cylinder);
calculate = (Button) findViewById(R.id.buttonCylCalc);
length = (EditText) findViewById(R.id.editCylLength);
height = (EditText) findViewById(R.id.editCylHeight);
depth = (EditText) findViewById(R.id.editCylDepth);
result = (TextView) findViewById(R.id.buttonCylResult);
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), (CharSequence) result, Toast.LENGTH_LONG).show();
try {
calculate();
} catch (Exception e) {
e.printStackTrace();
}
result.setText((CharSequence) result);
}
public TextView calculate() throws Exception {
// TODO Auto-generated method stub
double firstNum = Double.valueOf(length.getText().toString());
double secNum = Double.valueOf(height.getText().toString());
double thirdNum = Double.valueOf(depth.getText().toString());
radius = (secNum/2);
area = ((secNum*secNum)*3.14);
//liqVolume = (firstNum) * (radius*radius)(acos(radius-depth/radius))
// Cubic Volume
v = aSide * l;
// Fluid surface Area, Side
aSide = (r*r)*(3.14 / 2 -Math.acos(1-h/r)) - (r-h)*Math.sqrt(h*(2*r-h));
// Fluid Surface Area Top
aTop = 2*Math.sqrt((r*r)-((r-h)*(r-h) * l));
// Fluid Surface Area Bottom
b = fsal*l;
// Fluid Surface Area Total
FluidSurfaceAreaTotal = 2*aSide+aTop+b;
// Cylinder Radius
r = d/2;
// Cylinder Diameter
d = 2*r;
if (h <= r )
// Fluid Side Arc Length
fsal = 2*r*Math.acos((r-h)/r);
else if (h > r)
fsal = 2*r*(3.14-Math.acos((h-r)/r));
return result;
}
});
}
}
Here is a logcat:
10-18 05:24:38.893: E/AndroidRuntime(964): FATAL EXCEPTION: main
10-18 05:24:38.893: E/AndroidRuntime(964): java.lang.ClassCastException: android.widget.Button
10-18 05:24:38.893: E/AndroidRuntime(964): at com.dbryant423.fuel.volume.calculator.CalculateCylinder$1.onClick(CalculateCylinder.java:55 )
10-18 05:24:38.893: E/AndroidRuntime(964): at android.view.View.performClick(View.java:2408)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.view.View$PerformClick.run(View.java:8816)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.os.Handler.handleCallback(Handler.java:587)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.os.Handler.dispatchMessage(Handler.java:92)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.os.Looper.loop(Looper.java:123)
10-18 05:24:38.893: E/AndroidRuntime(964): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-18 05:24:38.893: E/AndroidRuntime(964): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 05:24:38.893: E/AndroidRuntime(964): at java.lang.reflect.Method.invoke(Method.java:521)
10-18 05:24:38.893: E/AndroidRuntime(964): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-18 05:24:38.893: E/AndroidRuntime(964): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-18 05:24:38.893: E/AndroidRuntime(964): at dalvik.system.NativeStart.main(Native Method)
I've been wracking my brains to try to figure out how to do the math on this, and I've not been able to find the answer to why it's crashing. I'm sure it's probably something simple that I've missed somewhere. If you need more information from the other files let me know, but this one seem the be the only one with the problem. I also know that there is unused variables that I've not removed yet.
result.setText((CharSequence) result);
This line cause Exception because you are casting Android View class to CharSequence Class.
Possible Solution:
Change return type of your method public TextView calculate() to
public String calculate()
Now in method public String calculate() return String of result fsal
And your button's Click() is something like,
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), (CharSequence) result, Toast.LENGTH_LONG).show();
String resultValue = "";
try {
resultValue = calculate();
} catch (Exception e) {
e.printStackTrace();
}
result.setText( resultValue);
}
result = (TextView) findViewById(R.id.buttonCylResult);
Are you casting properly? based on the naming, i would say that you are casting from a button to TextView. Try changing to,
result = (Button) findViewById(R.id.buttonCylResult);
Well, my program keeps giveing me a null point exception and I don't know why? I know it has something to do with the lvl variable, but I don't know what? What can I do to fix this problem?
Logcat:
03-18 16:14:55.852: ERROR/AndroidRuntime(277): FATAL EXCEPTION: main
03-18 16:14:55.852: ERROR/AndroidRuntime(277): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.games.think/com.games.think.Think}: java.lang.NullPointerException
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.os.Looper.loop(Looper.java:123)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invokeNative(Native Method)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at java.lang.reflect.Method.invoke(Method.java:521)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at dalvik.system.NativeStart.main(Native Method)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): Caused by: java.lang.NullPointerException
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at com.games.think.Think.onCreate(Think.java:38)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-18 16:14:55.852: ERROR/AndroidRuntime(277): ... 11 more
Here is some of my code:
package com.games.think;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
public class Think extends Activity implements OnClickListener{
int question = 1, lvl;
/** Called when the activity is first created. */
RadioButton lvl1;
RadioButton lvl2;
RadioButton lvl3;
RadioButton lvl4;
RadioButton lvl5;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(this);
Button level = (Button)findViewById(R.id.level);
level.setOnClickListener(this);
Button exit = (Button)findViewById(R.id.exit);
exit.setOnClickListener(this);
Button setLevel = (Button)findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
lvl1 = (RadioButton)findViewById(R.id.lvl1);
lvl2 = (RadioButton)findViewById(R.id.lvl2);
lvl3 = (RadioButton)findViewById(R.id.lvl3);
lvl4 = (RadioButton)findViewById(R.id.lvl4);
lvl5 = (RadioButton)findViewById(R.id.lvl5);
lvl = getLevel();
if(lvl == -1) {
lvl=getLevel();
}
}
#SuppressWarnings("null")
private int getLevel() {
String FILENAME = "think_level";
FileInputStream fis;
byte[] buffer = new byte[1000];
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
setLevel("1");
return -1;
}
try {
fis.read(buffer,0,1000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String level = buffer.toString();
int iLevel = Integer.valueOf(level);
return iLevel;
}
private void setLevel(String level) {
String FILENAME = "think_level";
String string = level;
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
switch( v.getId()){
case R.id.play:
setContentView(R.layout.play);
setQuestion();
case R.id.level:
setContentView(R.layout.level);
switch(getLevel()) {
case 1:
lvl1.setChecked(true);
case 2:
lvl2.setChecked(true);
case 3:
lvl3.setChecked(true);
case 4:
lvl4.setChecked(true);
case 5:
lvl5.setChecked(true);
}
case R.id.setLevel:
if(lvl1.isChecked()) {
setLevel("1");
}
if(lvl2.isChecked()) {
setLevel("2");
}
if(lvl3.isChecked()) {
setLevel("3");
}
if(lvl4.isChecked()) {
setLevel("4");
}
if(lvl5.isChecked()) {
setLevel("5");
}
}
}
private void setQuestion() {
}
}
Check if the button with id "setLevel" is in your main.xml. If it is somewhere else, you can not find it like this:
Button setLevel = (Button)findViewById(R.id.setLevel);
But you need an inflater.
If iunderstand this is 37-38 lines
Button setLevel = (Button)findViewById(R.id.setLevel);
setLevel.setOnClickListener(this);
Seems like setLevel is null. Is button with id setLevel described in xml layout ?
Button setLevel = (Button)findViewById(R.id.setLevel);
This line is not returning an object. Make sure you have the id right and that there is a button registered with it.