My application code is as follows,
public class Alarm extends MainActivity {
public String str;
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
str = "";
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str += "CB " + msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
str += " :";
str += "\n";
}
}
}
EditText user_value;
Button startalarm;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.third);
startalarm = (Button) findViewById(R.id.startalarm);
user_value = (EditText) findViewById(R.id.user_value);
startalarm.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(user_value.length()==0)
{
Toast.makeText(getBaseContext(), "Please enter a value.", Toast.LENGTH_LONG).show();
}
SQLiteDatabase aa = openOrCreateDatabase("MLIdata", MODE_WORLD_READABLE, null);
Cursor c = aa.rawQuery("SELECT CblocationName FROM MLITable WHERE CblocationCode = '"+str+"'", null);
c.moveToFirst();
c.getString(c.getColumnIndex("CblocationName"));
String sas = user_value.getText().toString();
if(sas==getString(c.getColumnIndex("CblocationName")))
{
//here comes the alarm code
Toast.makeText(getBaseContext(), "till here it has executed.", Toast.LENGTH_LONG).show();
Notification notification = new Notification(android.R.drawable.ic_popup_reminder,
"My Notification", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
}
});
}
}
Though there are no errors, when I run this code it force closes when I press the 'startalarm' button.
My log cat is as follows,
11-05 01:31:03.029: W/ResourceType(1554): No package identifier when getting value for resource number 0x00000000
11-05 01:31:03.029: W/dalvikvm(1554): threadid=1: thread exiting with uncaught exception (group=0x40018578)
11-05 01:31:03.029: E/AndroidRuntime(1554): FATAL EXCEPTION: main
11-05 01:31:03.029: E/AndroidRuntime(1554): android.content.res.Resources$NotFoundException: String resource ID #0x0
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.content.res.Resources.getText(Resources.java:201)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.content.res.Resources.getString(Resources.java:254)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.content.Context.getString(Context.java:183)
11-05 01:31:03.029: E/AndroidRuntime(1554): at my.project.mil.Alarm$1.onClick(Alarm.java:68)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.view.View.performClick(View.java:2485)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.view.View$PerformClick.run(View.java:9080)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.os.Handler.handleCallback(Handler.java:587)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.os.Looper.loop(Looper.java:130)
11-05 01:31:03.029: E/AndroidRuntime(1554): at android.app.ActivityThread.main(ActivityThread.java:3687)
11-05 01:31:03.029: E/AndroidRuntime(1554): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 01:31:03.029: E/AndroidRuntime(1554): at java.lang.reflect.Method.invoke(Method.java:507)
11-05 01:31:03.029: E/AndroidRuntime(1554): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-05 01:31:03.029: E/AndroidRuntime(1554): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-05 01:31:03.029: E/AndroidRuntime(1554): at dalvik.system.NativeStart.main(Native Method)
I've tried all the solutions given in the below link, yet none helped.
Android, string resource not found
Help required,
Thank you.
I had no idea my comment would fix your exception. I will put it as an answer so you can close this question.
Change this line:
if(sas==getString(c.getColumnIndex("CblocationName")))
to
if(sas.equals(getString(c.getColumnIndex("CblocationName"))))
Read up on String comparison if you don't understand why this should be like this.
Related
Hello guys I am making an Android app that convert from binary to decimal and I have made a class called Binary and a class called Decimal and a function in the Binary class that convert from decimal to binary
public Binary DtoB(Decimal decimal)
{
String temp = null;
do
{
if(decimal.decimal%2!=0)
temp+='1';
else
temp+='0';
decimal.decimal/=2;
}while(decimal.decimal>0);
while(temp.length()%4!=0)
temp+='0';
for(int i=temp.length()-1;i>=0;i--)
{
this.bn+=temp.charAt(i);
}
return this;
}
and in the activity there's a button that converts, but when I test and press on the button the app breaks
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d1.decimal=Integer.parseInt(e1.getText().toString());
b.DtoB(d1);
t1.setText(b.bn);
}
});
can any one help me please ???
Here is the logcat:
10-26 09:16:15.831: E/AndroidRuntime(280): FATAL EXCEPTION: main
10-26 09:16:15.831: E/AndroidRuntime(280): java.lang.NullPointerException
10-26 09:16:15.831: E/AndroidRuntime(280): at com.example.converter.MainActivity$1.onClick(MainActivity.java:34)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123) 10-26 09:16:15.831: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method) 10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
Try this...!
public class BinaryToDecimal {
public int getDecimalFromBinary(int binary){
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
decimal += tmp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
BinaryToDecimal bd = new BinaryToDecimal();
System.out.println("11 ===> "+bd.getDecimalFromBinary(11));
System.out.println("110 ===> "+bd.getDecimalFromBinary(110));
System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110));
}
}
check variable all are initialize perfectly . because some time objectc are created but it is null so can't work and throw java.lang.NullPointerException .....
b1 , d1 , b ,t1
I'm new in android programming. I'm writing simple application that should execute sql file, in first run. But it seems that this process take couple of seconds so I figure that application should show progressDialog while it will be executing sql file. But when I try to run application, dialog is showing with message "app has stopped ...". Please help me.
#Override
public void onCreate(SQLiteDatabase database)
{
String CREATE_BIBLE_TABLE = "CREATE TABLE bible (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"book INTEGER, " +
"chapter INTEGER NOT NULL, " +
"verse INTEGER NOT NULL, " +
"content TEXT" +
")";
database.execSQL(CREATE_BIBLE_TABLE);
new FirstLoadAsyncTask(database).execute();
}
public class FirstLoadAsyncTask extends AsyncTask<Void, Void, Void>
{
private SQLiteDatabase database;
private ProgressDialog progressDialog;
public FirstLoadAsyncTask(SQLiteDatabase database)
{
this.database = database;
}
#Override
protected void onPreExecute()
{
((Activity) context).runOnUiThread(new Runnable()
{
#Override
public void run()
{
progressDialog = ProgressDialog.show(context, "Loading...", "");
}
});
}
#Override
protected Void doInBackground(Void... params)
{
try
{
InputStream inputStream = context.getAssets().open("bible.sql");
execSqlFile(database, inputStream);
} catch(IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
Class extends SQLiteOpenHelper.
Edit:
Logcat:
01-06 18:27:53.221 14118-14118/pl.several27.Biblia_Warszawska E/Trace﹕ error opening trace file: No such file or directory (2)
01-06 18:27:53.891 14118-14118/pl.several27.Biblia_Warszawska I/Adreno200-EGL﹕ <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081_msm7627a_JB_REL_2.0.3_CL2820657_release_AU (CL2820657)
Build Date: 01/22/13 Tue
Local Branch:
Remote Branch: quic/jb_rel_2.0.3
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081 + NOTHING
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska E/copybit﹕ Error opening frame buffer errno=13 (Permission denied)
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska W/Adreno200-EGLSUB﹕ <updater_create_surface_state:342>: updater_create_surface_state failed to open copybit, error: -13
01-06 18:27:54.011 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x53be8000 size:1536000 offset:0 fd:61
01-06 18:27:54.021 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x5083a000 size:4096 offset:0 fd:63
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x541fb000 size:1536000 offset:0 fd:66
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50a50000 size:4096 offset:0 fd:68
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x54472000 size:1536000 offset:0 fd:70
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50c75000 size:4096 offset:0 fd:72
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x545e9000 size:1536000 offset:0 fd:74
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50d4c000 size:4096 offset:0 fd:76
01-06 18:27:57.231 14118-14118/pl.several27.Biblia_Warszawska D/book choosen﹕ 1
01-06 18:27:57.581 14118-14118/pl.several27.Biblia_Warszawska W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40ca4540)
01-06 18:27:57.601 14118-14118/pl.several27.Biblia_Warszawska E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{pl.several27.Biblia_Warszawska/pl.several27.Biblia_Warszawska.ChapterActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at pl.several27.Biblia_Warszawska.Database$FirstLoadAsyncTask.onPreExecute(Database.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at pl.several27.Biblia_Warszawska.Database.onCreate(Database.java:42)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
at pl.several27.Biblia_Warszawska.Database.countChapters(Database.java:148)
at pl.several27.Biblia_Warszawska.ChapterActivity.onCreate(ChapterActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
01-06 18:27:59.511 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ killProcess, pid=14118
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.VMStack.getThreadStackTrace(Native Method)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.Thread.getStackTrace(Thread.java:599)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ android.os.Process.killProcess(Process.java:956)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:108)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.NativeStart.main(Native Method)
Also I tried this way display progressdialog in non-activity class but it won't work too.
And here is whole application source code but without dialog: https://github.com/several27/BibliaWarszawska_Android
Please can anyone help me?
I do something like that on my application but I prefer to do that on background, so the user just don't have access to the screens that depend on my database...
You can try something like that:
public class BackgroundSyncService extends IntentService {
public static final String NOTIFICATION = "com.example.sync.service";
public static final String RESULT = "result";
public BackgroundSyncService() {
super("BackgroundSyncService");
}
#Override
protected void onHandleIntent(Intent intent) {
//Do here what you want with your database
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
Create a receiver (I use a inner class on my project)
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
//Do what you want here , like enable a section of your app
}
}
};
Then you need to register the service to your activity adding :
registerReceiver(receiver, new IntentFilter(BackgroundSyncService.NOTIFICATION));
Don't forget to unregister the receiver:
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Also don't forget to register your IntentService on the AndroidManifest.xml
<service android:name="com.example.service.BackgroundSyncService" />
EDIT
Also you need to include the call to start your service where you want, I start mine on App instance:
Intent intent = new Intent(this, BackgroundSyncService.class);
startService(intent);
EXPLANATION
First you are creating a service to do what you want, the service can do whatever you want, in your case you will fill a database...
After you have created this service, you will set when you want to start this service (the edit part)...
After that you will register your activity to listen the service thats why we have created the BroadcastReceiver, the BroadcastReceiver will be called when your Service execute the line:
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
I guess the better way when the app starts you present the user with a message/ an activity that is not database related or just use the splash screen at the time that it is loading and estimate the time it normally finish loading to be the timer of the splash screen
I am developing an android app... where I developed a table in MySql and table has certain results for values of 1-10 and all the values are entered seperately ...
in my android application when a particular value is displayed the result of that value has to be taken from the table... but it is not working correctly ...the message is getting like 'unfortunately application closed'... i am adding my code here... please check the code and if found any mistake pls help.....
Activity.java
public class FirstResult extends Activity
{
String pid;
TextView txtName;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://iascpl.com/app/get_product_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
//private static final String TAG_PID = "pid";
//private static final String TAG_NUMBER = "number";
//private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.firstresult_xm);
TextView txt1 = (TextView) findViewById (R.id.textView2);
txt1.setText(getIntent().getStringExtra("name10"));
pid = txt1.getText().toString();
new GetProductDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FirstResult.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (TextView) findViewById(R.id.textView3);
// display product data in EditText
txtName.setText(product.getString(TAG_DESCRIPTION));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
php file
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT *FROM prediction WHERE pid = $pid");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["number"] = $result["number"];
// $product["price"] = $result["price"];
$product["description"] = $result["description"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
my Logcat
11-05 11:44:12.701: E/AndroidRuntime(7643): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 11:44:12.701: E/AndroidRuntime(7643): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 11:44:12.701: E/AndroidRuntime(7643): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.example.numero.JSONParser.makeHttpRequest(JSONParser.java:63)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.example.numero.FirstResult$GetProductDetails$1.run(FirstResult.java:105)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.os.Handler.handleCallback(Handler.java:725)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.os.Looper.loop(Looper.java:137)
11-05 11:44:12.701: E/AndroidRuntime(7643): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-05 11:44:12.701: E/AndroidRuntime(7643): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 11:44:12.701: E/AndroidRuntime(7643): at java.lang.reflect.Method.invoke(Method.java:511)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-05 11:44:12.701: E/AndroidRuntime(7643): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-05 11:44:12.701: E/AndroidRuntime(7643): at dalvik.system.NativeStart.main(Native Method)
11-05 11:52:08.052: E/Trace(7805): error opening trace file: No such file or directory (2)
11-05 11:56:14.171: E/AndroidRuntime(7805): FATAL EXCEPTION: main
11-05 11:56:14.171: E/AndroidRuntime(7805): android.os.NetworkOnMainThreadException
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-05 11:56:14.171: E/AndroidRuntime(7805): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.example.numero.JSONParser.makeHttpRequest(JSONParser.java:63)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.example.numero.FirstResult$GetProductDetails$1.run(FirstResult.java:105)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.Handler.handleCallback(Handler.java:725)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.os.Looper.loop(Looper.java:137)
11-05 11:56:14.171: E/AndroidRuntime(7805): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 11:56:14.171: E/AndroidRuntime(7805): at java.lang.reflect.Method.invoke(Method.java:511)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-05 11:56:14.171: E/AndroidRuntime(7805): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-05 11:56:14.171: E/AndroidRuntime(7805): at dalvik.system.NativeStart.main(Native Method)
11-05 11:56:25.961: E/Trace(7893): error opening trace file: No such file or directory (2)
runOnUiThread(new Runnable() {
#Override
public void run()
{
// TODO Auto-generated method stub
try {
txt3.setText(product.getString(TAG_DESCRIPTION));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}else{
// product with pid not found
}
add this line after
/ get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (TextView) findViewById(R.id.textView3);
that will solve the issue
You need to post the stack trace of the problem. You will find it in your logcat view. Also, on a sidenote:
runOnUiThread(new Runnable() {
public void run() {
This doesnt make any sense at all at this place because you are basically running a background thread, then you synchronize it and run it on the main thread. Depending on your settings, that won't work because Android does not allow network operations on the main / UI thread.
Edit after LogCat was added:
It's exactly what I mentioned. Android does not allow you to run network traffic on the UI thread. Remove that runOnUiThread stuff from the runOnBackground.
Now to set the data you can two one of two things:
Add the runOnUiThread part where you set the textView. Something like:
runOnUiThread(new Runnable() {
public void run() {
TextView tv = findViewById...
tv.setText(...
}
}
Return the object you need. This is actually how AsyncTask is supposed to work:
In your AsyncTask's runOnBackground, you'd do:
return product.getString(TAG_DESCRIPTION)
Then, in onPostExecute you get that String and set it to your TextViews.
I have two methods to update and delete data in my app, I have implemeted try catches within my switch statement and am now getting the following error:
01-14 20:38:58.778: D/AndroidRuntime(273): Shutting down VM
01-14 20:38:58.778: W/dalvikvm(273): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-14 20:38:58.798: E/AndroidRuntime(273): FATAL EXCEPTION: main
01-14 20:38:58.798: E/AndroidRuntime(273): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.flybase2/com.example.flybase2.viewEdit}: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.os.Looper.loop(Looper.java:123)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.reflect.Method.invoke(Method.java:521)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-14 20:38:58.798: E/AndroidRuntime(273): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-14 20:38:58.798: E/AndroidRuntime(273): at dalvik.system.NativeStart.main(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): Caused by: java.lang.NullPointerException
01-14 20:38:58.798: E/AndroidRuntime(273): at com.example.flybase2.viewEdit.<init>(viewEdit.java:63)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstanceImpl(Native Method)
01-14 20:38:58.798: E/AndroidRuntime(273): at java.lang.Class.newInstance(Class.java:1429)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-14 20:38:58.798: E/AndroidRuntime(273): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
01-14 20:38:58.798: E/AndroidRuntime(273): ... 11 more
Can anyone see the issue? It works perfectly without the try catches.
Heres the class:
package com.example.flybase2;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class viewEdit extends Activity implements OnClickListener{
EditText namePassedEdit;
EditText numPassedEdit;
EditText emailPassedEdit;
EditText commentPassedEdit;
Button bUpdate;
Button bDelete;
long passedID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editview);
DBHandler displayEdit = new DBHandler(this, null, null);
Bundle extras = getIntent().getExtras();
if (extras != null) {
passedID = extras.getLong("passedID");
}
displayEdit.open();
String returnedNameToEdit = displayEdit.getName(passedID);
String returnedNumToEdit = displayEdit.getNum(passedID);
String returnedEmailToEdit = displayEdit.getEmail(passedID);
String returnedCommentToEdit = displayEdit.getComments(passedID);
namePassedEdit = (EditText) findViewById(R.id.inputNameEdit);
numPassedEdit = (EditText) findViewById(R.id.inputTelNoEdit);
emailPassedEdit = (EditText) findViewById(R.id.inputEmailEdit);
commentPassedEdit = (EditText) findViewById(R.id.inputCommentEdit);
bUpdate = (Button) findViewById (R.id.btnAddConEdit);
bDelete = (Button) findViewById (R.id.btnDeleteContact);
namePassedEdit.setText(returnedNameToEdit);
numPassedEdit.setText(returnedNumToEdit);
emailPassedEdit.setText(returnedEmailToEdit);
commentPassedEdit.setText(returnedCommentToEdit);
bUpdate.setOnClickListener(this);
bDelete.setOnClickListener(this);
}
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
#Override
public void onClick(View updateOrDeleteClicked) {
boolean check = true;
switch(updateOrDeleteClicked.getId()){
case (R.id.btnAddConEdit):
try
{
DBHandler updateData = new DBHandler(this, null, null);
updateData.open();
updateData.updateData(passedID, nameEdit, telEdit, emailEdit, commentEdit);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
case (R.id.btnDeleteContact):
try
{
DBHandler deleteContact = new DBHandler(this, null, null);
deleteContact.open();
deleteContact.deleteData(passedID);
}
catch (Exception e)
{
check = false;
Dialog d = new Dialog(this);
d.setTitle("Contact failed to be deleted.");
TextView txt = new TextView(this);
txt.setText("Fail");
d.setContentView(txt);
d.show();
}
finally
{
if(check = true);
{
Dialog e = new Dialog(this);
e.setTitle("Contact deleted.");
TextView txt = new TextView(this);
txt.setText("Success");
e.setContentView(txt);
e.show();
}
}
break;
}
}
}
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
These lines aren't inside a method, and you can't use them like that. You're getting a null pointer on namePassedEdit because it's trying to initialize them when the class is created, and they aren't assigned anything yet.
One issue I see here is:
if(check = true); //This ends if statement here and here you are assigning true to check nothing more than that..
I guess what you need here is:
if(check){....}
The main problem I can find is that you close the braces for your onCreate on line 59. Leaving the following lines between functions.
String nameEdit = namePassedEdit.getText().toString();
String telEdit = numPassedEdit.getText().toString();
String emailEdit = emailPassedEdit.getText().toString();
String commentEdit = commentPassedEdit.getText().toString();
If you move these up into the onCreate it will probably fix your issue. Also as #Nambari said in their answer, in your if statements you are checking if check was set to true. You need to change this to:
if(check)
I'm trying to write a speech to text app for android. Now the app doesn't crash on the emulator, but when I upload it to a samsung galaxy s 1900 I get following error messages in eclipse:
11-05 17:43:48.814: I/dalvikvm(3092): Could not find method com.example.speechtotext.MainActivity.getActionBar, referenced from method com.example.speechtotext.MainActivity.onCreate
11-05 17:43:48.818: W/dalvikvm(3092): VFY: unable to resolve virtual method 3036: Lcom/example/speechtotext/MainActivity;.getActionBar ()Landroid/app/ActionBar;
11-05 17:43:48.818: D/dalvikvm(3092): VFY: replacing opcode 0x6e at 0x0009
11-05 17:43:48.818: D/dalvikvm(3092): VFY: dead code 0x000c-0061 in Lcom/example/speechtotext/MainActivity;.onCreate (Landroid/os/Bundle;)V
11-05 17:43:48.896: D/AndroidRuntime(3092): Shutting down VM
11-05 17:43:48.900: W/dalvikvm(3092): threadid=1: thread exiting with uncaught exception (group=0x4001d7d0)
11-05 17:43:48.900: E/AndroidRuntime(3092): FATAL EXCEPTION: main
11-05 17:43:48.900: E/AndroidRuntime(3092): java.lang.NoSuchMethodError: com.example.speechtotext.MainActivity.getActionBar
11-05 17:43:48.900: E/AndroidRuntime(3092): at com.example.speechtotext.MainActivity.onCreate(MainActivity.java:40)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.os.Looper.loop(Looper.java:123)
11-05 17:43:48.900: E/AndroidRuntime(3092): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-05 17:43:48.900: E/AndroidRuntime(3092): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 17:43:48.900: E/AndroidRuntime(3092): at java.lang.reflect.Method.invoke(Method.java:521)
11-05 17:43:48.900: E/AndroidRuntime(3092): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
11-05 17:43:48.900: E/AndroidRuntime(3092): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
11-05 17:43:48.900: E/AndroidRuntime(3092): at dalvik.system.NativeStart.main(Native Method)
11-05 17:44:11.343: I/dalvikvm(3092): threadid=3: reacting to signal 3
11-05 17:44:12.724: E/dalvikvm(3092): Failed to write stack traces to /data/anr/traces.txt (805 of 2366): Unknown error: 0
11-05 17:44:22.165: I/Process(3092): Sending signal. PID: 3092 SIG: 9
firmware version 2.2 on the phone.
When running in emulator the program just sais that speech isn't supported in the emulator, no crash though.
This my code:
package com.example.speechtotext;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.widget.EditText;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.content.Intent;
import java.util.Locale;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements OnClickListener,
OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech myTTS;
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().setDisplayHomeAsUpEnabled(true);
Button speakButton = (Button) findViewById(R.id.speak);
speakButton.setOnClickListener(this);
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
// Get display items for later interaction
Button speakButton2 = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
speakButton2.setOnClickListener(this);
} else {
speakButton2.setEnabled(false);
speakButton2.setText("Recognizer not present");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
// Indien men op de speakbutton klikt
public void onClick(View arg0) {
EditText enteredText = (EditText) findViewById(R.id.enter);
String words = enteredText.getText().toString();
speakWords(words);
if (arg0.getId() == R.id.btn_speak) {
startVoiceRecognitionActivity();
}
}
// Zorgt voor de spraak
private void speakWords(String speech) {
// myTTS.speak(speech, TextToSpeech.QUEUE_ADD, null); zorgt dat de app
// het toevoegt aan de queue zodat het wacht tot de vorige speech
// opdracht uitgesproken is
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
}
// Controleren of de data beschikbaar is
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
myTTS = new TextToSpeech(this, this);
} else {
Intent installTTSIntent = new Intent();
installTTSIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTTSIntent);
}
}
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
&& resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it
// could have heard
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
// Taal juist zetten en indien er een fout is geeft men een foutboodschap
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
}
I've checked that the min API isn't to high, but eclipse has set that to 2.2 so I think thats fine.
Someone an idea what could be wrong or how to debug?
Kind regards,
The problem is that you are trying to use ActionBar on device running Android 2.2 (API level 8), but ActionBar was added in API level 11.
So you have basically two options here:
Don't use ActionBar in your app.
Use ActionBarSherlock library, it backports action bar back to Android 2.x (though you still need to make some minor changes in your code, read the docs of ActionBarSherlock for more details).