My Android app crashes when trying to store SQLite data - java

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.

Related

at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)

I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:397) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:353) 
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful

How do I pull a string from an array in Android?

I have an android app that is a streaming radio.
To change the radio stations, there is a drop down menu (based on a spinner) that allows the user to select the radio station and then it will load.
Problem: when I leave it as default, the first channel plays fine ...
when I try to chose another station, the app crashes.
I am using the new Android Studio.
I think that I am not getting the string for the URL from the array.
Can someone help me see what my mistake is??
Here is my code:
import android.annotation.TargetApi;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class AndroidMediaPlayerExample extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2000, backwardTime = 2000;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
//String url = "http://radio.miraath.net:7000";
//String url = new String[]{"http://radio.miraath.net:7000", "http://radio.miraath.net:7010", "http://radio.miraath.net:7020", "http://radio.miraath.net:7030","http://radio.miraath.net:7040", };
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout of the Activity
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.spinner1);
String[] items = new String[]{"Radio 1: Arabic", "Radio 2: Live Arabic", "Radio 3: Qur'an", "Radio 4: English Radio", "Radio 5: Arabic Radio 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
//initialize views
initializeViews();
}
public void initializeViews(){
songName = (TextView) findViewById(R.id.songName);
mediaPlayer = MediaPlayer.create(this, R.raw.sample_song);
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
songName.setText("Radio1 - Miraath.net");
seekbar.setMax((int) finalTime);
seekbar.setClickable(false);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
mediaPlayer.release();
switch (position) {
case 0:
// Whatever you want to happen when the first item gets selected
url = "http://radio.miraath.net:7000";
break;
case 1:
// Whatever you want to happen when the second item gets selected
url = "http://radio.miraath.net:7010";
break;
case 2:
// Whatever you want to happen when the thrid item gets selected
url = "http://radio.miraath.net:7020";
break;
case 3:
// Whatever you want to happen when the thrid item gets selected
url = "http://radio.miraath.net:7030";
break;
case 4:
// Whatever you want to happen when the thrid item gets selected
url = "http://radio.miraath.net:7040";
break;
}
}
// play mp3 song
public void play(View view) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaing
double timeRemaining = finalTime - timeElapsed;
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
}
UPDATE!!!
Here is the error from the log:
03-14 19:20:10.413 1191-1284/system_process W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
03-14 19:20:10.422 1191-1416/system_process I/ActivityManager﹕ START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.javacodegeeks.androidmediaplayerexample/.AndroidMediaPlayerExample (has extras)} from uid 10008 on display 0
03-14 19:20:10.457 4043-4043/? E/libprocessgroup﹕ failed to make and chown /acct/uid_10065: Read-only file system
03-14 19:20:10.457 4043-4043/? W/Zygote﹕ createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-14 19:20:10.457 4043-4043/? I/art﹕ Not late-enabling -Xcheck:jni (already on)
03-14 19:20:10.461 1191-3310/system_process I/ActivityManager﹕ Start proc com.javacodegeeks.androidmediaplayerexample for activity com.javacodegeeks.androidmediaplayerexample/.AndroidMediaPlayerExample: pid=4043 uid=10065 gids={50065, 9997, 3003} abi=x86
03-14 19:20:10.493 4043-4050/? E/art﹕ Failed sending reply to debugger: Broken pipe
03-14 19:20:10.493 4043-4050/? I/art﹕ Debugger is no longer active
03-14 19:20:10.515 4043-4043/? D/AndroidRuntime﹕ Shutting down VM
03-14 19:20:10.515 4043-4043/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.javacodegeeks.androidmediaplayerexample, PID: 4043
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.javacodegeeks.androidmediaplayerexample/com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample}: java.lang.ClassCastException: com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample cannot be cast to android.widget.AdapterView$OnItemSelectedListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassCastException: com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample cannot be cast to android.widget.AdapterView$OnItemSelectedListener
at com.javacodegeeks.androidmediaplayerexample.AndroidMediaPlayerExample.onCreate(AndroidMediaPlayerExample.java:42)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Thanks!!
You have not added listener on your spinner. Do it in this manner after your adapter is set
dropdown.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
Also you activity has to implement OnItemSelectedListener
public class AndroidMediaPlayerExample extends Activity implements OnItemSelectedListener

On button click uri intent works in android 4.1.2, but does not work on android 2.3.7

I have the following Activity:
package com.example.myapp;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.Toast;
public class HomeActivity extends Activity implements AnimationListener {
// Animation
Animation animFadein;
Animation animFadeout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_start);
// load the animation
animFadein = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_in);
animFadeout = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_out);
// set animation listener
animFadein.setAnimationListener(this);
ImageButton homepage =(ImageButton)findViewById(R.id.homepage);
ImageButton new_b =(ImageButton)findViewById(R.id.new_b);
ImageButton view_b =(ImageButton)findViewById(R.id.view_b);
ImageButton home_b =(ImageButton)findViewById(R.id.home_b);
ImageButton info_b =(ImageButton)findViewById(R.id.info_b);
Button back_b =(Button)findViewById(R.id.back_b);
Button site =(Button)findViewById(R.id.site);
homepage.startAnimation(animFadein);
//Click on screen to start
homepage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View homepage = (View)findViewById(R.id.homepage);
View startpage = (View)findViewById(R.id.startpage);
homepage.setVisibility(View.GONE);
homepage.startAnimation(animFadeout);
startpage.setVisibility(View.VISIBLE);
startpage.setAnimation(animFadein);};});
new_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences values = getSharedPreferences("valoar", 0);
SharedPreferences.Editor editor = values.edit();
editor.clear();
editor.commit();
View startpage = (View)findViewById(R.id.startpage);
startpage.setAnimation(animFadeout);
Intent intent = new Intent(HomeActivity.this,QuestionsActivity.class);
startActivity(intent);}});
home_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View homepage = (View)findViewById(R.id.homepage);
View startpage = (View)findViewById(R.id.startpage);
homepage.setVisibility(View.VISIBLE);
homepage.startAnimation(animFadein);
startpage.startAnimation(animFadeout);
startpage.setVisibility(View.GONE);};});
info_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View startpage = (View)findViewById(R.id.startpage);
View infopage = (View)findViewById(R.id.infopage);
ScrollView info_s = (ScrollView)findViewById(R.id.info_s);
infopage.setVisibility(View.VISIBLE);
info_s.setVisibility(View.VISIBLE);
infopage.startAnimation(animFadein);
startpage.startAnimation(animFadeout);
startpage.setVisibility(View.GONE);};});
back_b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View startpage = (View)findViewById(R.id.startpage);
View infopage = (View)findViewById(R.id.infopage);
ScrollView info_s = (ScrollView)findViewById(R.id.info_s);
infopage.setVisibility(View.GONE);
info_s.setVisibility(View.GONE);
infopage.startAnimation(animFadeout);
startpage.startAnimation(animFadein);
startpage.setVisibility(View.VISIBLE);};});
**site.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent internetIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.i-amapp.com"));
internetIntent.setComponent(new ComponentName("com.android.browser","com.android.browser.BrowserActivity"));
internetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(internetIntent);};});**
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public void onAnimationEnd(Animation arg0) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
/**
* Back button listener.
* Will close the application if the back button pressed twice.
*/
#Override
public void onBackPressed()
{
int backButtonCount = 0;
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this, "Press the x button to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}
It works very well in android 4.1.2, but in android 2.3.7 it crashes, and Logcat displays:
D/AndroidRuntime(2172): Shutting down VM
W/dalvikvm(2172): threadid=1: thread exiting with uncaught exception (group=0x40018560)
E/AndroidRuntime(2172): FATAL EXCEPTION: main
E/AndroidRuntime(2172): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.HomeActivity}: java.lang.NullPointerException
E/AndroidRuntime(2172): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
E/AndroidRuntime(2172): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
E/AndroidRuntime(2172): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
E/AndroidRuntime(2172): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
E/AndroidRuntime(2172): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(2172): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(2172): at android.app.ActivityThread.main(ActivityThread.java:3835)
E/AndroidRuntime(2172): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2172): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(2172): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
E/AndroidRuntime(2172): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
E/AndroidRuntime(2172): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(2172): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2172): at com.example.myapp.HomeActivity.onCreate(HomeActivity.java:107)
E/AndroidRuntime(2172): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
E/AndroidRuntime(2172): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
E/AndroidRuntime(2172): ... 11 more
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 61K, 50% free 2724K/5379K, external 0K/0K, paused 44ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 4K, 50% free 2730K/5379K, external 507K/513K, paused 43ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 1K, 50% free 2736K/5379K, external 1068K/1524K, paused 43ms
D/dalvikvm(3117): GC_EXTERNAL_ALLOC freed 1K, 50% free 2741K/5379K, external 1669K/2086K, paused
This is all that logcat is displaying. I can't figure out what is the problem!
Why does it crash in android 2.3?

I create intent to link to other interface but end up force close

This is my Login.java code
package com.pmss;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Login extends Activity {
Button login, register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.register);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//startActivity(new Intent());
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(new Intent(intent));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
}
This is my Register.java
package com.pmss;
import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Register extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.pmss.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
/*MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.register, menu);
return super.onCreateOptionsMenu(menu);*/
getMenuInflater().inflate(R.menu.register, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
// searchView.setIconifiedByDefault(false);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, RegisterNextPart.class);
EditText editText = (EditText) findViewById(R.id.nametext);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openSearch(){
}
public void openSettings(){
}
}
I wonder is it anything to do with this coding:
register = (Button) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(new Intent(intent));
}
});
When run on my mobile phone and I tap register button which end up force close the application. Anybody help me? really new to ADT
And This is my logcat
11-23 22:09:32.029: W/dalvikvm(15739): VFY: unable to resolve interface method 7433: Landroid/view/MenuItem;.getActionView ()Landroid/view/View;
11-23 22:09:32.169: D/AndroidRuntime(15739): Shutting down VM
11-23 22:09:32.169: W/dalvikvm(15739): threadid=1: thread exiting with uncaught exception (group=0x40018578)
11-23 22:09:32.169: E/AndroidRuntime(15739): FATAL EXCEPTION: main
11-23 22:09:32.169: E/AndroidRuntime(15739): java.lang.NoSuchMethodError: android.view.MenuItem.getActionView
11-23 22:09:32.169: E/AndroidRuntime(15739): at com.pmss.Register.onCreateOptionsMenu(Register.java:36)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.app.Activity.onCreatePanelMenu(Activity.java:2158)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:224)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:70)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.os.Handler.handleCallback(Handler.java:587)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.os.Handler.dispatchMessage(Handler.java:92)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.os.Looper.loop(Looper.java:130)
11-23 22:09:32.169: E/AndroidRuntime(15739): at android.app.ActivityThread.main(ActivityThread.java:3687)
11-23 22:09:32.169: E/AndroidRuntime(15739): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 22:09:32.169: E/AndroidRuntime(15739): at java.lang.reflect.Method.invoke(Method.java:507)
11-23 22:09:32.169: E/AndroidRuntime(15739): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-23 22:09:32.169: E/AndroidRuntime(15739): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-23 22:09:32.169: E/AndroidRuntime(15739): at dalvik.system.NativeStart.main(Native Method)
Change your register button setOnClickListener code to
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Login.this, Register.class);
startActivity(intent);
}
});
And Don't Forget to add Activity in your Manifest File
<activity
android:name=".Register"
android:label="#string/app_name">
</activity>
Ther are so many cases why this error is occured.
1) May be you have forgot to add Register activity to your Menifest File.
2) The ID which you are providing for registed is wrong
and so other also, It's very hard to tell without logcat. But this are cases which might occur.

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