[Q] Error receiving Intent from IntentService - Java for Android App Development

I'm trying to make an app that displays and image which will be downloaded in background in an IntentService class. When the IntentService finishes to download it sends the intent to be catched by a BroadcastReceiver in the MainActivity but I'm getting this error:
Code:
07-17 14:27:21.003 19189-19189/com.example.matt95.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.matt95.myapplication, PID: 19189
java.lang.RuntimeException: Error receiving broadcast Intent { act=TRANSACTION_DONE flg=0x10 (has extras) } in [email protected]
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java)
at android.os.Handler.handleCallback(Handler.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
************at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java)
************at android.os.Handler.handleCallback(Handler.java)
************at android.os.Handler.dispatchMessage(Handler.java)
************at android.os.Looper.loop(Looper.java)
************at android.app.ActivityThread.main(ActivityThread.java)
************at java.lang.reflect.Method.invokeNative(Native Method)
************at java.lang.reflect.Method.invoke(Method.java)
This is MainActivity class:
Code:
package com.example.matt95.myapplication;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MyActivity extends Activity {
ProgressDialog pd;
// Custom BroadcastReceiver for catching and showing images
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@Override
protected void onStart() {
super.onStart();
Intent i = new Intent(this, ImageIntentService.class);
i.putExtra("url", "http://samsung-wallpapers.com/uploads/allimg/130527/1-13052F02118.jpg");
startService(i);
pd = ProgressDialog.show(this, "Fetching image", "Go intent service go!");
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ImageIntentService.TRANSACTION_DONE);
registerReceiver(imageReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(imageReceiver);
}
private BroadcastReceiver imageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String location = intent.getExtras().getString("imageLocation");
if (location == null || location.length() == 0) {
String failedString = "Failed to download image";
Toast.makeText(context, failedString, Toast.LENGTH_LONG).show();
}
File imageFile = new File(location);
if (!imageFile.exists()) {
pd.dismiss();
String downloadFail = "Unable to download the image";
Toast.makeText(context, downloadFail, Toast.LENGTH_LONG).show();
return;
}
Bitmap image = BitmapFactory.decodeFile(location);
ImageView iv = (ImageView) findViewById(R.id.show_image);
iv.setImageBitmap(image);
pd.dismiss();
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the IntentService class:
Code:
package com.example.matt95.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageIntentService extends IntentService {
private File cacheDir;
private static final String CACHE_FOLDER = "/myapp/image_cache/";
public static String TRANSACTION_DONE = "com.example.matt95.myapplication.ImageIntentService.TRANSACTION_DONE";
//Constructor method
public ImageIntentService() {
super("ImageIntentService");
}
@Override
public void onCreate() {
super.onCreate();
String tmpLocation = Environment.getExternalStorageDirectory().getPath() + CACHE_FOLDER;
cacheDir = new File(tmpLocation);
if (!cacheDir.exists())
cacheDir.mkdirs();
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent.hasExtra("url")) {
String remoteUrl = intent.getExtras().getString("url");
String imageLocation;
String fileName = remoteUrl.substring(remoteUrl.lastIndexOf(File.separator) + 1);
File tmpImage = new File(cacheDir + "/" + fileName);
if (tmpImage.exists()) {
imageLocation = tmpImage.getAbsolutePath();
notifyFinished(imageLocation, remoteUrl);
stopSelf();
return;
}
try {
URL url = new URL(remoteUrl);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
if (httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
InputStream is = httpCon.getInputStream();
FileOutputStream fos = new FileOutputStream(tmpImage);
writeStream(is, fos);
fos.flush();
fos.close();
is.close();
imageLocation = tmpImage.getAbsolutePath();
notifyFinished(imageLocation, remoteUrl);
} catch (Exception e) {
Log.e("Service", "Failed!", e);
}
}
}
private void writeStream(InputStream is, OutputStream fos) throws Exception {
byte buffer[] = new byte[80000];
int read = is.read(buffer);
while (read != -1) {
fos.write(buffer, 0, read);
read = is.read(buffer);
}
}
private void notifyFinished(String imageLocation, String remoteUrl) {
Intent i = new Intent(TRANSACTION_DONE);
i.putExtra("imageLocation", imageLocation);
i.putExtra("url", remoteUrl);
ImageIntentService.this.sendBroadcast(i);
}
}
And this is the Manifest file:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.matt95.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ImageIntentService" />
</application>
</manifest>
What am I doing wrong?

Code:
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
tells you there, you are asking an object that is of type "x" that is NULL to do something on line 74

Why not just use the picasso library or similar to download the image asynchronously in the background?
Sent from my HTC One using Tapatalk

deanwray said:
Code:
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
tells you there, you are asking an object that is of type "x" that is NULL to do something on line 74
Click to expand...
Click to collapse
Thanks, I knew that but I'lll take a closer look at the code again :good:
Jonny said:
Why not just use the picasso library or similar to download the image asynchronously in the background?
Sent from my HTC One using Tapatalk
Click to expand...
Click to collapse
I'm a beginner in Android application so I don't have the proper knowledge right now, thanks for the suggestion though, I'll definitely try to take a look at that library :good:

matt95 said:
Thanks, I knew that but I'lll take a closer look at the code again :good:
I'm a beginner in Android application so I don't have the proper knowledge right now, thanks for the suggestion though, I'll definitely try to take a look at that library :good:
Click to expand...
Click to collapse
Better use asynctask for loading images
Sent from my Moto G using XDA Premium 4 mobile app

arpitkh96 said:
Better use asynctask for loading images
Sent from my Moto G using XDA Premium 4 mobile app
Click to expand...
Click to collapse
Yeah but I also need to download it and then load it, and it's not good to download that amount of data on the main thread

matt95 said:
Yeah but I also need to download it and then load it, and it's not good to download that amount of data on the main thread
Click to expand...
Click to collapse
AsyncTask runs in the background on a separate thread via the doInBackground method.
Sent from my HTC One using Tapatalk

Also, when there is a possibility that one of the objects included in the intent is null you can trap the error with a try/catch around the sendBroadcast() to prevent the exception from crashing the entire app.

Related

Need help with a title menu

Hey everyone,
I'm working on a minesweeper-like game for my independent project in school this semester, but I'm running into a but of trouble with the title screen. What I'm trying to do is have a seperate activity launch for MainGame.java and Options.java when their respective buttons are clicked. When I click on Start, it launches the MainGame activity, but whenever I click on Options the app force closes. It's really weird because I'm doing essentially the same thing with both buttons. Here's the code for Title.java, let me know if you need to see anything else:
Code:
package com.freekyfrogy.treasure;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Title extends Activity implements OnClickListener {
Button buttonStart, buttonScores, buttonOptions, buttonExit;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.title);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(this);
buttonScores = (Button) findViewById(R.id.buttonScores);
buttonScores.setOnClickListener(this);
buttonOptions = (Button) findViewById(R.id.buttonOptions);
buttonOptions.setOnClickListener(this);
buttonExit = (Button) findViewById(R.id.buttonExit);
buttonExit.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonStart:
if(buttonStart.isPressed()){
startActivity(new Intent(getApplicationContext(),MainGame.class));
}
break;
case R.id.buttonScores:
if(buttonScores.isPressed()){
Toast.makeText(this, R.string.toastComingSoon, Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonOptions:
if(buttonOptions.isPressed()){
startActivity(new Intent(getApplicationContext(), Options.class));
}
break;
case R.id.buttonExit:
if(buttonExit.isPressed()){
finish();
}
break;
}
}
}
If i had to guess id say you didnt declare both activities in your manifest...
what does the debugger say is the problem?
I declared them both in the manifest, here's it's XML code:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.freekyfrogy.treasure"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
<activity android:name="Title"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="MainGame"
android:screenOrientation="portrait">
</activity>
<activity android:name="Options"
android:screenOrientation="portrait">
</activity>
</application>
</manifest>
and the Error I'm getting is this:
Code:
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): FATAL EXCEPTION: main
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.freekyfrogy.treasure/com.freekyfrogy.treasure.Options}: java.lang.NullPointerException
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1768)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:936)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.os.Handler.dispatchMessage(Handler.java:99)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.os.Looper.loop(Looper.java:123)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.main(ActivityThread.java:3812)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.reflect.Method.invokeNative(Native Method)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.reflect.Method.invoke(Method.java:507)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at dalvik.system.NativeStart.main(Native Method)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): Caused by: java.lang.NullPointerException
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.Activity.findViewById(Activity.java:1647)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at com.freekyfrogy.treasure.Options.<init>(Options.java:16)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.Class.newInstanceImpl(Native Method)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.Class.newInstance(Class.java:1409)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1656)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): ... 11 more
Can you post your Options class? It looks to me like there may be something wrong in there.
Options class:
Code:
package com.freekyfrogy.treasure;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Options extends Activity implements OnClickListener {
int intX = 5;
int intY = 5;
EditText sizeX = (EditText) findViewById(R.id.editX);
EditText sizeY = (EditText) findViewById(R.id.editY);
Button setXY = (Button) findViewById(R.id.setXY);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
setXY.setOnClickListener(this);
}
public void onClick(View v) {
String strX = sizeX.getText().toString();
String strY = sizeY.getText().toString();
intX = Integer.parseInt(strX);
intY = Integer.parseInt(strY);
Toast.makeText(this, "this is a toast: "+ intX+ " "+ intY, Toast.LENGTH_SHORT).show();
}
}
Hi freekyfrogy,
you should declare there controls of in onCreate method of Options activity
EditText sizeX = (EditText) findViewById(R.id.editX);
EditText sizeY = (EditText) findViewById(R.id.editY);
Button setXY = (Button) findViewById(R.id.setXY);
your option activity code look like this:
package com.freekyfrogy.treasure;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Options extends Activity implements OnClickListener {
int intX = 5;
int intY = 5;
Button setXY = (Button) findViewById(R.id.setXY);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
EditText sizeX = (EditText) findViewById(R.id.editX);
EditText sizeY = (EditText) findViewById(R.id.editY);
setXY.setOnClickListener(this);
}
public void onClick(View v) {
String strX = sizeX.getText().toString();
String strY = sizeY.getText().toString();
intX = Integer.parseInt(strX);
intY = Integer.parseInt(strY);
Toast.makeText(this, "this is a toast: "+ intX+ " "+ intY, Toast.LENGTH_SHORT).show();
}
}
Oh I see now!!! Thanks so much, now it's not force closing haha

Browser not working! Please help :(

Hi, I was trying to make a browser. But obviously, its not working. Please help me out. I will be providing all the codes here:
Thanks in advance ...
manifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.browser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-premission android:name="android.content.permissions.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.browser.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.browser.ta"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.TA" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.class:
Code:
package com.example.browser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText search = (EditText) findViewById(R.id.editText1);
WebView wb = (WebView) findViewById(R.id.webView1);
Button back = (Button) findViewById(R.id.button2);
Button forward = (Button) findViewById(R.id.button1);
Button Bsearch = (Button) findViewById(R.id.dd);
String s = search.getText().toString();
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wb.getSettings().setBuiltInZoomControls(true);
wb.getSettings().setJavaScriptEnabled(true);
wb.getSettings().setLoadWithOverviewMode(true);
wb.getSettings().setSavePassword(true);
wb.getSettings().setAllowFileAccess(true);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.setWebViewClient(t);
wb.loadUrl("http://www.google.com");
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.dd: // search
ProgressDialog d = ProgressDialog.show(this, "loading",
"Please wait");
wb.loadUrl("http://" + s);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
case R.id.button2: // back
if (wb.canGoBack())
wb.goBack();
break;
case R.id.button1: // forward
if (wb.canGoForward())
wb.goForward();
break;
}
}
}
ta.class:
Code:
package com.example.browser;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ta extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView v, String url) {
v.loadUrl(url);
return true;
}
}
Logcat?
nikwen said:
Logcat?
Click to expand...
Click to collapse
Sorry, I completely forgot, about that!!
Here it is:
Code:
07-14 16:12:46.367: E/AndroidRuntime(287): FATAL EXCEPTION: main
07-14 16:12:46.367: E/AndroidRuntime(287): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.browser/com.example.browser.MainActivity}: java.lang.NullPointerException
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.os.Handler.dispatchMessage(Handler.java:99)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.os.Looper.loop(Looper.java:123)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.reflect.Method.invokeNative(Native Method)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.reflect.Method.invoke(Method.java:521)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-14 16:12:46.367: E/AndroidRuntime(287): at dalvik.system.NativeStart.main(Native Method)
07-14 16:12:46.367: E/AndroidRuntime(287): Caused by: java.lang.NullPointerException
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.Activity.findViewById(Activity.java:1637)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.Class.newInstanceImpl(Native Method)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.Class.newInstance(Class.java:1429)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
07-14 16:12:46.367: E/AndroidRuntime(287): ... 11 more
Read This http://forum.xda-developers.com/showthread.php?t=2325164
then look at your logcat
Code:
07-14 16:12:46.367: E/AndroidRuntime(287): Caused by: java.lang.NullPointerException
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.Activity.findViewById(Activity.java:1637)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17)
then count from the top, and your error is your edittext
I looked at the edit-text. But i still cannot find any wrong. However, I modified one of my buttons with this:
Code:
case R.id.dd: // search
wb.loadUrl("http://" + search.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
Still. no help...
Code:
07-14 16:12:46.367: E/AndroidRuntime(287): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.browser/com.example.browser.MainActivity}: java.lang.NullPointerException
What is this about??
I think, there is something wrong with the manifest, Please take a look at it!
read nikwens debugging guide I linked again.
then here
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17
thats the name of your app, and the line you have the problem at.
nullpointers could be a million things, look for your app and the line it errors on.
also intent.action.TA isnt a thing. take that out.
out of ideas said:
read nikwens debugging guide I linked again.
then here
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17
thats the name of your app, and the line you have the problem at.
nullpointers could be a million things, look for your app and the line it errors on.
also intent.action.TA isnt a thing. take that out.
Click to expand...
Click to collapse
Hey, thanks for linking it.
It even tells you that the method which fails is findViewById().
nikwen said:
Hey, thanks for linking it.
It even tells you that the method which fails is findViewById().
Click to expand...
Click to collapse
Yeah, you were right, there were couple of wrong ids, in that code. But I have edited all of them now.. Still the app is crashing and I am getting the same error, for "findByView".
I am also pasting, the new code and the UI xml.
activity_main.xml:
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >
<EditText
android:id="@+id/editText1"
android:layout_width="291dp"
android:layout_height="wrap_content"
android:layout_x="0dp"
android:layout_y="4dp"
android:hint="Enter Search!" />
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentBottom="true"
android:layout_below="@+id/back" />
<Button
android:id="@+id/s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="@+id/back"
android:text="Search" />
<Button
android:id="@+id/dd"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_toRightOf="@+id/s"
android:text="Forward" />
<Button
android:id="@+id/back"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/dd"
android:layout_alignBottom="@+id/dd"
android:layout_toRightOf="@+id/dd"
android:text="Back" />
</RelativeLayout>
MainActivity:
Code:
package com.example.browser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText search = (EditText) findViewById(R.id.editText1);
WebView wb = (WebView) findViewById(R.id.webView1);
Button back = (Button) findViewById(R.id.s);
Button forward = (Button) findViewById(R.id.back);
Button Bsearch = (Button) findViewById(R.id.dd);
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.dd: // search
wb.loadUrl("http://" + search.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
case R.id.back: // back
if (wb.canGoBack())
wb.goBack();
break;
case R.id.s: // forward
if (wb.canGoForward())
wb.goForward();
break;
}
}
}
Please help me out! I know I am dumb. But I am learning it all by myself, without a mentor at the age of 16. Its little complex for me. I have spent, a lot of time finding the error. But its not working.
It doesn't like trying to find the view where you are declaring your variables. The findviewbyid should be moved in to your oncreate.
This works:
Code:
public class MainActivity extends Activity implements OnClickListener {
EditText search;
WebView wb;
Button back;
Button forward;
Button Bsearch;
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
After looking in to the reason why it would crash, my only educated guess is because you are trying to find the view without the view being set. View is set in the oncreate method.
zalez said:
It doesn't like trying to find the view where you are declaring your variables. The findviewbyid should be moved in to your oncreate.
This works:
Code:
public class MainActivity extends Activity implements OnClickListener {
EditText search;
WebView wb;
Button back;
Button forward;
Button Bsearch;
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
After looking in to the reason why it would crash, my only educated guess is because you are trying to find the view without the view being set. View is set in the oncreate method.
Click to expand...
Click to collapse
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
I modified my code, with this.. But, its still crashing
Post your entire MainActivity.class. I copied all of your code and changed what I posted back and do not get a crash.
This is working for me:
Code:
package com.example.browser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText search;
WebView wb;
Button back;
Button forward;
Button Bsearch;
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.dd: // search
wb.loadUrl("http://" + search.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
case R.id.back: // back
if (wb.canGoBack())
wb.goBack();
break;
case R.id.s: // forward
if (wb.canGoForward())
wb.goForward();
break;
}
}
}
hiphop12ism said:
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
I modified my code, with this.. But, its still crashing
Click to expand...
Click to collapse
It is still crashing. However, keep that code as it is right. The setContentView method needs to be called before getting the views.
In your xml there are some errors though:
You always use @+id/...
Use that just for android:id="@+id/myId".
Everywhere else do it without the plus, e.g. android:layout_below="@id/asdf".
The plus tells the compiler to create a new id. However, you do not want it to create a new id in android:layout_below but to use an already existing id.
Are all ids in the xml you load with setContentView? Is the logcat still the same? Could you please highlight the line which makes it crash?
nikwen said:
It is still crashing. However, keep that code as it is right. The setContentView method needs to be called before getting the views.
In your xml there are some errors though:
You always use @+id/...
Use that just for android:id="@+id/myId".
Everywhere else do it without the plus, e.g. android:layout_below="@id/asdf".
The plus tells the compiler to create a new id. However, you do not want it to create a new id in android:layout_below but to use an already existing id.
Are all ids in the xml you load with setContentView? Is the logcat still the same? Could you please highlight the line which makes it crash?
Click to expand...
Click to collapse
Actually, I fixed it. I made a new project. I thought of another way of making the browser.
I realised, there were lots of mistakes in the xml file.
here are my new codes. (Thank you everbody its over finally)
the UI
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="enter url" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="100"
android:orientation="horizontal" >
<Button
android:id="@+id/s"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="search" />
<Button
android:id="@+id/back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="back" />
<Button
android:id="@+id/forward"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="35"
android:text="forward" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:layout_width="match_parent"
android:layout_height="308dp"
android:id="@+id/wd" />
</LinearLayout>
</LinearLayout>
MainActivity:
Code:
package com.example.asd;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
EditText et;
Button search, back, forward;
WebView wb;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
search = (Button) findViewById(R.id.s);
back = (Button) findViewById(R.id.back);
forward = (Button) findViewById(R.id.forward);
wb = (WebView) findViewById(R.id.wd);
search.setOnClickListener(this);
wb.getSettings().setJavaScriptEnabled(true);
wb.getSettings().setAllowFileAccess(true);
wb.getSettings().setBuiltInZoomControls(true);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.s:
wb.loadUrl(et.getText().toString());
wb.setWebViewClient(new callb());
break;
}
}
private class callb extends WebViewClient {
[user=439709]@override[/user]
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
wb.loadUrl(url);
return true;
}
}
}
But can you tell me, how can I make it more advanced. Like, when hit a editText on a website itslf.. Nothing Happens
You have to request focus on the webview:
wb.requestFocus(View.FOCUS_DOWN);

[GUIDE] Adding Splash Screen to Your Application.

A splash screen is an image that appears while a game or program is loading. Splash screen can be used to show app / company logo for a couple of second.
In this GUIDE we are going to learn how to implement splash screen in your android application.
I have created a application with name com.example.assassin.splash.screen.test
Browse through res/drawable-hdpi and paste a png image into the folder.
[Note: Image used in this guide is with name = splash.png , height=800 , width=480]
Now browse to res/layout folder and create a splash activity.
To create a splash activity Right click on layout folder and select New>Other>Android>Android XML File
And create a file called splash
Having problem? See the snapshots.
ScreenShot
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Now open your splash.xml file and paste the following codes.
Code:
[B]<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/splash"
>
</LinearLayout>[/B]
Save it.
Browse to src/com.example.assassin.splash.screen.test and create a new class name Splash
ScreenShot
Code for Splash.java
Code:
package com.example.assassin.splash.screen.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class Splash extends Activity{
@Override
protected void onCreate(Bundle assassin) {
// TODO Auto-generated method stub
super.onCreate(assassin);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.assassin.splash.screen.STARTINGPOINT");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Save It.
ScreenShot
Now open AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.assassin.splash.screen.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Splash"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.assassin.splash.screen.test.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.example.assassin.splash.screen.STARTINGPOINT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Save It.
ScreenShot
Well now you have successfully created a splash sceen activity for your application.
Designing MainActivity.xml is up to you.
MainActivity.xml used in this guide looks like this:
ScreenShot
​
Please correct me if the code goes wrong somewhere.
Saurabh Shah
Code:
package com.example.arpit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
public class New extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.arpit.Extra");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Log says activity com.example.arpit.Extra not found
But it is present there .Is there any format to be included with the like .class or .java
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
Code:
package com.example.arpit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
public class New extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.arpit.Extra");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Log says activity com.example.arpit.Extra not found
But it is present there .Is there any format to be included with the like .class or .java
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
I can see where your code is going wrong.
you have included com.example.arpit.Extra in the new intent.
it should be com.example.arpit.STARTINGPOINT
Here is the corrected code for your class.
Code:
package com.example.arpit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
public class New extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.arpit.STARTINGPOINT");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Hope this helps u.
a-ssassi-n said:
I can see where your code is going wrong.
you have included com.example.arpit.Extra in the new intent.
it should be com.example.arpit.STARTINGPOINT
Here is the corrected code for your class.
Code:
package com.example.arpit;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
public class New extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000); //time to display splash screen in millisecond
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent openStartingPoint = new Intent("com.example.arpit.STARTINGPOINT");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Hope this helps u.
Click to expand...
Click to collapse
I thought it was a name of activity.thanks
Edit-Same error
Code:
/ActivityManager( 1087): START {act=com.example.arpit.STARTINGPOINT u=0} from pid 3386
W/dalvikvm( 3386): threadid=11: thread exiting with uncaught exception (group=0x40aba300)
E/AndroidRuntime( 3386): FATAL EXCEPTION: Thread-153
E/AndroidRuntime( 3386): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.arpit.STARTINGPOINT }
E/AndroidRuntime( 3386): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
E/AndroidRuntime( 3386): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)
E/AndroidRuntime( 3386): at android.app.Activity.startActivityForResult(Activity.java:3351)
E/AndroidRuntime( 3386): at android.app.Activity.startActivityForResult(Activity.java:3312)
E/AndroidRuntime( 3386): at android.app.Activity.startActivity(Activity.java:3522)
E/AndroidRuntime( 3386): at android.app.Activity.startActivity(Activity.java:3490)
E/AndroidRuntime( 3386): at com.example.arpit.New$100000000.run(New.java:30)
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
I thought it was a name of activity.thanks
Edit-Same error
Code:
/ActivityManager( 1087): START {act=com.example.arpit.STARTINGPOINT u=0} from pid 3386
W/dalvikvm( 3386): threadid=11: thread exiting with uncaught exception (group=0x40aba300)
E/AndroidRuntime( 3386): FATAL EXCEPTION: Thread-153
E/AndroidRuntime( 3386): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.example.arpit.STARTINGPOINT }
E/AndroidRuntime( 3386): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
E/AndroidRuntime( 3386): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)
E/AndroidRuntime( 3386): at android.app.Activity.startActivityForResult(Activity.java:3351)
E/AndroidRuntime( 3386): at android.app.Activity.startActivityForResult(Activity.java:3312)
E/AndroidRuntime( 3386): at android.app.Activity.startActivity(Activity.java:3522)
E/AndroidRuntime( 3386): at android.app.Activity.startActivity(Activity.java:3490)
E/AndroidRuntime( 3386): at com.example.arpit.New$100000000.run(New.java:30)
Sent from my GT-S5570 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
Still getting Error.??
Upload your project file as a zip.
i will take a look at that after my exams are over(after 3days)
Thankyou.
a-ssassi-n said:
Still getting Error.??
Upload your project file as a zip.
i will take a look at that after my exams are over(after 3days)
Thankyou.
Click to expand...
Click to collapse
Problem solved by
New.this,Extra.class rather than "com.example.Arpit.STARTINGPOINT"
Sent from my GT-S5570 using XDA Premium 4 mobile app
Great :good:

[Q] Same shell command works from console and doesn't work from Activity

//sorry for my english, if any
Hi. I'm using AIDE right on my device (Xperia NeoV, 4.1.B.0.587, root)
And i'm trying to inject key events through the same shell command:
"input keyevent 25" via "su", both in AIDE Console and separated Activity.
//volume-down key is not my target, just good for tests. I've tried different keys, same result.
Part of the code:
Code:
try {
java.lang.Process p = Runtime.getRuntime().exec("su");
DataOutputStream dos = new DataOutputStream(p.getOutputStream());
dos.writeBytes("input keyevent 25\n");
dos.flush();
} catch (IOException ex) {
//log any errors
}
So, when it goes in AIDE ConsoleApp - it pushes down volume.
But when it executes from my Activity - nothing happens (no error messages in log, dos != null);
Maybe there should be some specific permission on manifest?
"android.permission.ACCESS_SUPERUSER" - no changes.
Maybe there should be some trick in code? Or(and?) i'm very stupid. Also, maybe somewhere a whole listing of _simple_ keyInjection project exists?
I managed to solve it already. I'm using this class now:
public void RunAsRoot(String[] cmds){
Process p = null;
try {
p = Runtime.getRuntime().exec("su");
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
try {
os.writeBytes(tmpCmd+"\n");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
os.writeBytes("exit\n");
} catch (IOException e) {
e.printStackTrace();
}
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
Click to expand...
Click to collapse
Then simply call it via
String[] commands = {"command1", "command2", "command3", ...};
RunAsRoot(commands);
Click to expand...
Click to collapse
Thanks anyways!
Click to expand...
Click to collapse
Credits: @KrauseDroid
Our original thread i took it from:
http://forum.xda-developers.com/showthread.php?t=2725173
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Masrepus said:
Credits: @KrauseDroid
Our original thread i took it from:
http://forum.xda-developers.com/showthread.php?t=2725173
Click to expand...
Click to collapse
I saw that thread before creating own, and tried solutions from it. They works same way - only from ConsoleApp in AIDE.
Also, last method is the same as I'm already using, but I've tried to copy code in project - no progress.
In addition:
- superuser rights granted to both.
- test "ls" command put into dos object gives me same list of current dir in both projects, so commands seems to run.
Listing:
MainActivity:
Code:
package com.tsk.mk;
import android.app.*;
import android.content.*;
import android.os.*;
import android.widget.*;
import java.io.*;
public class MainActivity extends Activity {
public static TextView logView;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
logView = (TextView) findViewById(R.id.log);
log("creating sercice");
final MainActivity me = this;
new Thread() {
[user=439709]@override[/user]
public void run() {
log("thread.run");
startService(new Intent(me, MissedKeysService.class));
log("thread: service shoul'd be created");
}
}.start();
log("end of MA.onCreate method");
}
static void log(String message) {
logView.setText(logView.getText() + "\n" + message);
}
}
MissedKeysService:
Code:
package com.tsk.mk;
import android.app.*;
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.view.*;
import java.io.*;
public class MissedKeysService extends Service {
private WindowManager windowManager;
private MissedKeysView mkv;
private WindowManager.LayoutParams params;
private DataOutputStream dos;
[user=439709]@override[/user]
public IBinder onBind(Intent intent) {
MainActivity.log("onBind called o_o");
return null;
}
[user=439709]@override[/user]
public void onCreate() {
MainActivity.log("Service.onCreate");
super.onCreate();
try {
java.lang.Process p = Runtime.getRuntime().exec("su");
dos = new DataOutputStream(p.getOutputStream());
} catch (IOException ex) {
MainActivity.log(ex.getMessage());
dos = null;
}
windowManager = (WindowManager)
getSystemService(WINDOW_SERVICE);
mkv = new MissedKeysView(this, this);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
params.width = MissedKeysView.keySize;
params.height = MissedKeysView.keySize;
windowManager.addView(mkv, params);
MainActivity.log("Service started");
}
[user=439709]@override[/user]
public void onDestroy () {
super.onDestroy ();
if (mkv != null) windowManager.removeView(mkv);
MainActivity.log("Ssrvice is ended");
}
public void extend(boolean state) {
params.height = mkv.keySize * (state ? MissedKeysView.keys : 1);
windowManager.updateViewLayout(mkv, params);
}
public void sendKey(int code) {
if (dos == null) MainActivity.log("dos is null");
try {
dos.writeBytes("input keyevent " + code + "\n");
dos.flush();
MainActivity.log("" + code);
} catch (IOException e) {
MainActivity.log("wtf?");
}
}
}
MissedKeysView:
Code:
package com.tsk.mk;
import android.content.*;
import android.graphics.*;
import android.view.*;
import android.view.View.*;
import java.io.*;
public class MissedKeysView extends View
implements OnTouchListener {
final static int keySize = 64;
final static String[] labels = {":", "+", "-", "^", "v", "o", "<", ">"};
final private int[] codes = {-1, 24, 25, 19, 20, 23, 21, 22};
final static int keys = 3; //max shown keys
MissedKeysService mks;
Paint bgP; //background
Paint hbgP; //highlighted bg
Paint tP; //text
int selected = -1; //active key
public MissedKeysView(Context context, MissedKeysService mks) {
super(context);
this.mks = mks;
bgP = new Paint();
bgP.setARGB(64, 128, 128, 128);
hbgP = new Paint();
hbgP.setARGB(64, 255, 128, 0);
tP = new Paint();
tP.setARGB(128, 255, 255, 255);
tP.setTextSize(keySize);
tP.setTextAlign(Paint.Align.CENTER);
setOnTouchListener(this);
}
[user=439709]@override[/user]
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for(int i=0; i<getHeight()/keySize; i++) {
canvas.drawCircle(keySize/2,
keySize/2 + i*keySize, keySize/2,
(i == selected ? hbgP : bgP));
canvas.drawText(labels[i], keySize/2, i*keySize + keySize*3/4, tP);
}
}
[user=439709]@override[/user]
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
selected = (int) (event.getY()/keySize);
if (selected == 0) mks.extend((int) getHeight() <= keySize);
else mks.sendKey(codes[selected]);
break;
case MotionEvent.ACTION_UP:
selected =-1;
}
invalidate();
return super.onTouchEvent(event);
}
}
AndroidManifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsk.mk"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="11" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MissedKeysService"
android:exported="true" >
</service>
</application>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
<uses-permission android:name="android.permission.INJECT_EVENTS" />
</manifest>
@Torsionick do you have the permission INJECT_EVENTS
---------------------------------
Phone : Nexus 4
OS:
Pure KitKat 4.4.2 stock, no root, no mods
---------------------------------
4d 61 73 72 65 70 75 73 20 66 74 77
Gesendet von Tapatalk
Masrepus said:
@Torsionick do you have the permission INJECT_EVENTS
Click to expand...
Click to collapse
Thanks for participating in solving.
The reason was somewhere else - after executing "export LD_LIBRARY_PATH=/system/lib" all works fine. Thread is over.

[Q] Sendng data through Bluetooth between 2 Android devices is not working

Hi! I am trying to create an Android app which sends a message through Bluetooth from a device to another device. I am beginner in Android programming, so I have found a source code, which should do this. The problem is, that somehow I can't connect the 2 devices. I wrote this problem to some Android forums, but nobody could give me a satisfying answer. Please help me, Any answer would be appreciated which helps me to solve this problem.
Source code:
MainActivity.java:
Code:
package com.example.proba2x8;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
//@Override
//protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
//}
//}
//public class MainActivity extends ActionBarActivity {
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
EditText myTextbox;
TextView myLabel;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
String address;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
try {
Button sendButton = (Button) findViewById(R.id.send);
Button openButton = (Button) findViewById(R.id.open);
Button findButton = (Button) findViewById(R.id.bFind);
myTextbox = (EditText) findViewById(R.id.editText);
myLabel = (TextView) findViewById(R.id.textView);
openButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
openBT();
} catch (IOException ex) {
}
}
});
// send data typed by the user to be printed
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sendData();
} catch (IOException ex) {
}
}
});
findButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
findBT();
}
});
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// This will find a bluetooth device
void findBT() {
try {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
myLabel.setText("No bluetooth adapter available");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// Salaxy S4 is the name of the bluetooth device
if (device.getName().equals("Xperia mini pro")) {
mmDevice = device;
address = device.getAddress();
break;
}
}
}
myLabel.setText("Bluetooth Device Found," + address);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Tries to open a connection to the bluetooth device
void openBT() throws IOException {
try {
// Standard SerialPortService ID
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
myLabel.setText("1");
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// After opening a connection to bluetooth device,
// we have to listen and check if a data were sent to be printed.
void beginListenForData() {
try {
final Handler handler = new Handler();
// This is the ASCII code for a newline character
final byte delimiter = 10;
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()
&& !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
myLabel.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This will send data to be printed by the bluetooth
*/
void sendData() throws IOException {
try {
// the text typed by the user
String msg = myTextbox.getText().toString();
msg += "\n";
Log.w("MainActivity", msg);
mmOutputStream.write(msg.getBytes());
// tell the user data were sent
myLabel.setText("Data Sent");
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml:
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Text Here" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<Button
android:id="@+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/send"
android:layout_alignBottom="@+id/send"
android:layout_alignRight="@+id/linearLayout1"
android:text="Open" />
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/linearLayout1"
android:layout_marginTop="15dp"
android:text="Send" />
<TextView
android:id="@+id/recievedText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/send"
android:layout_below="@+id/send"
android:layout_marginTop="20dp"
android:text="Received Text" />
<TextView
android:id="@+id/rtArea"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/recievedText"
android:layout_alignParentBottom="true"
android:layout_below="@+id/recievedText"
android:layout_marginTop="20dp"
android:text="Received Text Will be Displayed Here..." />
<Button
android:id="@+id/bFind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/open"
android:layout_centerHorizontal="true"
android:text="Find" />
</RelativeLayout>
LogCat errors:
Code:
12-04 03:08:27.452: E/BluetoothEventLoop.cpp(1184): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/2002/hci0/dev_90_C1_15_37_AB_E7
12-04 03:08:27.732: W/System.err(1978): java.io.IOException: Service discovery failed
12-04 03:08:27.732: W/System.err(1978): at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:377)
12-04 03:08:27.742: W/System.err(1978): at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:201)
12-04 03:08:27.742: W/System.err(1978): at com.example.proba2x8.MainActivity.openBT(MainActivity.java:147)
12-04 03:08:27.742: W/System.err(1978): at com.example.proba2x8.MainActivity$1.onClick(MainActivity.java:74)
12-04 03:08:27.742: W/System.err(1978): at android.view.View.performClick(View.java:2418)
12-04 03:08:27.742: W/System.err(1978): at android.view.View.onTouchEvent(View.java:4233)
12-04 03:08:27.742: W/System.err(1978): at android.widget.TextView.onTouchEvent(TextView.java:6645)
12-04 03:08:27.742: W/System.err(1978): at android.view.View.dispatchTouchEvent(View.java:3763)
12-04 03:08:27.742: W/System.err(1978): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:968)
12-04 03:08:27.742: W/System.err(1978): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:968)
12-04 03:08:27.742: W/System.err(1978): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:968)
12-04 03:08:27.752: W/System.err(1978): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
12-04 03:08:27.752: W/System.err(1978): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
12-04 03:08:27.752: W/System.err(1978): at android.app.Activity.dispatchTouchEvent(Activity.java:2064)
12-04 03:08:27.752: W/System.err(1978): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
12-04 03:08:27.752: W/System.err(1978): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
12-04 03:08:27.752: W/System.err(1978): at android.os.Handler.dispatchMessage(Handler.java:99)
12-04 03:08:27.752: W/System.err(1978): at android.os.Looper.loop(Looper.java:123)
12-04 03:08:27.752: W/System.err(1978): at android.app.ActivityThread.main(ActivityThread.java:4370)
12-04 03:08:27.752: W/System.err(1978): at java.lang.reflect.Method.invokeNative(Native Method)
12-04 03:08:27.762: W/System.err(1978): at java.lang.reflect.Method.invoke(Method.java:521)
12-04 03:08:27.762: W/System.err(1978): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-04 03:08:27.762: W/System.err(1978): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-04 03:08:27.762: W/System.err(1978): at dalvik.system.NativeStart.main(Native Method)
12-04 03:08:32.082: E/BluetoothEventLoop.cpp(1184): event_filter: Received signal org.bluez.Device:PropertyChanged from /org/bluez/2002/hci0/dev_90_C1_15_37_AB_E7
I am going to write, what am I doing, while I get this error:
At first, I installed this app to both of my devices. When I start this app, a message pops up, which asks me to turn on bluetooth and set discoverablity forr 300 seconds. I click ok. Then I click the find button. This should find the device, which is called "Xperia Mini Pro". When the Bluetooth Device Found message is shown, I click the open button. And here comes the error.
Please help me to solve this problem, thanks.
If you look in the log you can find the error easily
12-04 03:08:27.742: W/System.err(1978): at com.example.proba2x8.MainActivity.openBT(MainActivity.java:147)
Line 147 of MainActivity is causing you the error of java.io.IOException: Service discovery failed
I'd suggest searching for the java.io.IOException: Service discovery failed error on Google, chances are you are not the first to have this problem.

Categories

Resources