Android - InputStreamReader not working - java

I want to get a String from a website, and convert it to a Array. It is working in eclipse, but if I want to use it in an Android-App it wont work. I know, it must be a stupid mistake but I dont know where it is.
InternetHandler:
package de.blender4me.einkaufsliste;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Pattern;
public class internetHandler {
//Einkaufsplaner-API aufrufen
public static String[] getList(){
InputStream is = null;
try
{
URL url = new URL("https://einkaufsplaner.blender4me.de/api.php?name=Username&pass=SuperSecretPass&addValue=&removeValue=");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String Values = null;
for(int i = 0; i < 4; ++i){
Values = in.readLine();
}
in.close();
String[] List = Values.split( Pattern.quote( ";" ) );
return List;
}
catch ( Exception e ) {
e.printStackTrace();
}
finally {
if ( is != null )
try { is.close(); } catch ( IOException e ) { }
}
String[] error = {"error"};
return error;
}
}
Main
package de.blender4me.einkaufsliste;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
//Widgets
Button addItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//listView
populateListView();
//register Widgets
addItem =(Button) findViewById(R.id.addItem);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
//Alert
public void openDialog(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Zur Einkaufsliste hinzufügen");
alert.setMessage(" ");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Bestätigen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
// Do something with value!
}
});
alert.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
//listView erstellen
private void populateListView() {
// Liste auslesen
String[] values = internetHandler.getList();
//Liste konvertieren
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.listview_item, //Genutztes Layout
values); //Genutzter Array
//listView einstellen
ListView list = (ListView) findViewById(R.id.listView);
list.setAdapter(adapter);
}
}
Manifest
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Light.NoActionBar.Fullscreen"
>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
It always returns the error-array, but idk why :C
logcat:
11-07 15:18:24.425: E/Trace(642): error opening trace file: No such
file or directory (2) 11-07 15:18:24.925: W/System.err(642):
android.os.NetworkOnMainThreadException 11-07 15:18:24.925:
W/System.err(642): at
android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-07 15:18:24.935: W/System.err(642): at
java.net.InetAddress.lookupHostByName(InetAddress.java:385) 11-07
15:18:24.935: W/System.err(642): at
java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 11-07
15:18:24.935: W/System.err(642): at
java.net.InetAddress.getAllByName(InetAddress.java:214) 11-07
15:18:24.935: W/System.err(642): at
libcore.net.http.HttpConnection.(HttpConnection.java:70) 11-07
15:18:24.935: W/System.err(642): at
libcore.net.http.HttpConnection.(HttpConnection.java:50) 11-07
15:18:24.935: W/System.err(642): at
libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
11-07 15:18:24.935: W/System.err(642): at
libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-07 15:18:24.935: W/System.err(642): at
libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 11-07
15:18:24.935: W/System.err(642): at
libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
11-07 15:18:24.945: W/System.err(642): at
libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
11-07 15:18:24.945: W/System.err(642): at
libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
11-07 15:18:24.945: W/System.err(642): at
libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
11-07 15:18:24.945: W/System.err(642): at
libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239) 11-07
15:18:24.945: W/System.err(642): at
libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
11-07 15:18:24.945: W/System.err(642): at
libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
11-07 15:18:24.945: W/System.err(642): at
libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
11-07 15:18:24.955: W/System.err(642): at
java.net.URL.openStream(URL.java:462) 11-07 15:18:24.955:
W/System.err(642): at
de.blender4me.einkaufsliste.internetHandler.getList(internetHandler.java:21)
11-07 15:18:24.955: W/System.err(642): at
de.blender4me.einkaufsliste.MainActivity.populateListView(MainActivity.java:100)
11-07 15:18:24.955: W/System.err(642): at
de.blender4me.einkaufsliste.MainActivity.onCreate(MainActivity.java:37)
11-07 15:18:24.955: W/System.err(642): at
android.app.Activity.performCreate(Activity.java:5008) 11-07
15:18:24.955: W/System.err(642): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-07 15:18:24.955: W/System.err(642): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
11-07 15:18:24.965: W/System.err(642): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-07 15:18:24.965: W/System.err(642): at
android.app.ActivityThread.access$600(ActivityThread.java:130) 11-07
15:18:24.965: W/System.err(642): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-07 15:18:24.965: W/System.err(642): at
android.os.Handler.dispatchMessage(Handler.java:99) 11-07
15:18:24.965: W/System.err(642): at
android.os.Looper.loop(Looper.java:137) 11-07 15:18:24.965:
W/System.err(642): at
android.app.ActivityThread.main(ActivityThread.java:4745) 11-07
15:18:24.965: W/System.err(642): at
java.lang.reflect.Method.invokeNative(Native Method) 11-07
15:18:24.965: W/System.err(642): at
java.lang.reflect.Method.invoke(Method.java:511) 11-07 15:18:24.975:
W/System.err(642): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-07 15:18:24.975: W/System.err(642): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-07
15:18:24.975: W/System.err(642): at
dalvik.system.NativeStart.main(Native Method) 11-07 15:18:26.455:
D/gralloc_goldfish(642): Emulator without GPU emulation detected.

Your problem is here (in the stacktrace) :
android.os.NetworkOnMainThreadException
You're making a request in the MainThread which is forbiden with Android to avoid heavy treatments on UI (making this will block the UI).
Use an AsyncTask instead.
An example of AsyncTask to start from something :
private class LongOperation extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
InternetHandler ih = new InternetHandler();
String[] values = ih.getList();
}
#Override
protected void onPostExecute(String result) {
//Liste konvertieren
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.listview_item, //Genutztes Layout
values); //Genutzter Array
//listView einstellen
ListView list = (ListView) findViewById(R.id.listView);
list.setAdapter(adapter);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
Call it with :
LongOperation lo = new LongOperation();
lo.execute();

The problem is you are trying to perform HTTP request on application's UI thread.
You should do it inside AsyncTask.

Related

NullPointerException error in Android: Unable to instantiate

Hello Everyone!
I am having a hard-time in correcting this error that I am facing while developing an android app. I tried to run in an emulator, but it crashes and gives the nullpointerexception error. Then, I made a new project and from scratch copied those files into a new project, and still the same error. Then, I made a part of the app into a new project, and still it gives the same error.
The error is something to do with launching the activity the I am using.
Below are the given necessary files, I hope someone can guide me to the right direction and tell what mistake am I doing. Thanks alot!
DISPLAYPOINTS.JAVA
package com.example.safedrive;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.text.Html;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayPoints extends Activity {
String name = "Ammaar";
TextView display_points;
Button btn_start = (Button) findViewById(R.id.btnStart); //Start Button Variable
String displayPoints;
InputStream is=null;
String result=null;
String line=null;
int points;
int code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_points);
TextView lblName = (TextView) findViewById(R.id.lblName);
display_points = (TextView) findViewById(R.id.lblCurrPoints); //POINTS TO DISPLAY IN
lblName.setText(Html.fromHtml("Welcome <b>" + name + "! </b>"));
new Insert().execute();
btn_start.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//MainScreen.IsStarted=true;
//SpeedPoints start = new SpeedPoints();
//Intent i = new Intent(getApplicationContext(), SpeedPoints.class);
//startActivity(i);
Toast.makeText(getApplicationContext(), "The app has started monitoring your drive...",
Toast.LENGTH_LONG).show();
//start.startAnimation();
}
});
}
class Insert extends AsyncTask<String, Void, String> {
// Do the long-running work in here
protected String doInBackground(String... args) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("fname", name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ammar123.net84.net/capstone/displayPoints.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
points=(json_data.getInt("pointss"));
displayPoints = Integer.toString(points);
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
return displayPoints;
}//End of doInBackground method
protected void onPostExecute(String displaypoints) {
display_points.setText(displayPoints);
Toast.makeText(getBaseContext(), "Points Retrieved!",
Toast.LENGTH_SHORT).show();
}//End of onPostExecute
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_points, 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);
}
}
MANIFEST FILE
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.safedrive"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.safedrive.DisplayPoints"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
LOGCAT ERRORS:
06-09 18:52:55.467: ERROR/ResourceType(87): Style contains key with bad entry: 0x01010479
06-09 18:52:56.567: ERROR/AndroidRuntime(771): FATAL EXCEPTION: main
06-09 18:52:56.567: ERROR/AndroidRuntime(771): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.safedrive/com.example.safedrive.DisplayPoints}: java.lang.NullPointerException
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1879)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.access$600(ActivityThread.java:122)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.os.Handler.dispatchMessage(Handler.java:99)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.os.Looper.loop(Looper.java:137)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.main(ActivityThread.java:4340)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at java.lang.reflect.Method.invokeNative(Native Method)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at java.lang.reflect.Method.invoke(Method.java:511)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at dalvik.system.NativeStart.main(Native Method)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): Caused by: java.lang.NullPointerException
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.Activity.findViewById(Activity.java:1794)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at com.example.safedrive.DisplayPoints.<init>(DisplayPoints.java:34)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at java.lang.Class.newInstanceImpl(Native Method)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at java.lang.Class.newInstance(Class.java:1319)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870)
06-09 18:52:56.567: ERROR/AndroidRuntime(771): ... 11 more
put this line
btn_start = (Button) findViewById(R.id.btnStart); //Start Button Variable
after
setContentView(R.layout.display_points);
findViewById is only possible after the layout is defined.

NullPionter Exception when passing string via Bundle

I am trying to pass a String form one activity to another in my app, however I keep getting a null pointer error. This is what shows up in my LogCat:
12-29 02:49:03.256: D/(663): HostConnection::get() New Host Connection established 0x96cb850, tid 663
12-29 02:49:06.288: W/KeyCharacterMap(663): No keyboard for id 0
12-29 02:49:06.288: W/KeyCharacterMap(663): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
12-29 02:49:09.600: D/AndroidRuntime(663): Shutting down VM
12-29 02:49:09.600: W/dalvikvm(663): threadid=1: thread exiting with uncaught exception (group=0xb5f444f0)
12-29 02:49:09.604: E/AndroidRuntime(663): FATAL EXCEPTION: main
12-29 02:49:09.604: E/AndroidRuntime(663): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld3/com.example.helloworld3.FloorPlan}: java.lang.NullPointerException
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.os.Handler.dispatchMessage(Handler.java:99)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.os.Looper.loop(Looper.java:130)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-29 02:49:09.604: E/AndroidRuntime(663): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 02:49:09.604: E/AndroidRuntime(663): at java.lang.reflect.Method.invoke(Method.java:507)
12-29 02:49:09.604: E/AndroidRuntime(663): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-29 02:49:09.604: E/AndroidRuntime(663): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-29 02:49:09.604: E/AndroidRuntime(663): at dalvik.system.NativeStart.main(Native Method)
12-29 02:49:09.604: E/AndroidRuntime(663): Caused by: java.lang.NullPointerException
12-29 02:49:09.604: E/AndroidRuntime(663): at com.example.helloworld3.FloorPlan.onCreate(FloorPlan.java:24)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-29 02:49:09.604: E/AndroidRuntime(663): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-29 02:49:09.604: E/AndroidRuntime(663): ... 11 more
12-29 02:49:12.316: D/(677): HostConnection::get() New Host Connection established 0x96c5790, tid 677
This is my ManActivity.java:
package com.example.helloworld3;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract.RawContacts.Data;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText destination = (EditText)findViewById(R.id.roomdinput);
final Button floorPlan = (Button)findViewById(R.id.floorPlanButton);
floorPlan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
String roomName = destination.getText().toString();
Bundle myb = new Bundle();
myb.putString("key1", roomName);
Intent a = new Intent(MainActivity.this, FloorPlan.class);
a.putExtras(myb);
startActivity(a);
startActivity(new Intent("com.example.helloworld3.FLOORPLAN"));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
}
And this is my FloorPan.java:
package com.example.helloworld3;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FloorPlan extends Activity{
DrawView2 drawView;
String roomName2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.floorplan);
Bundle myb2= getIntent().getExtras();
roomName2 = myb2.getString("key1");
drawView = new DrawView2(this);
drawView.setBackgroundResource(R.drawable.tait1st);
setContentView(drawView);
}
public class DrawView2 extends View {
Paint paint = new Paint();
float ux, dx, rx,lx;
public String getRoomName(){
return roomName2;
}
public void setCoordinates(){
if(roomName2 == "C154"){
ux =90;
dx = 250;
rx = 90;
lx = 400;
}else {
ux =76;
dx = 98;
rx = 140;
lx = 300;
}
};
public DrawView2(Context context) {
super(context);
paint.setColor(Color.RED);
//roomName2 = drawView.getTag();
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawLine(ux, dx , rx, lx, paint);
canvas.drawLine(20, 0, 0, 20, paint);
canvas.drawCircle(150, 400, 30, paint);
}
}
}
Thank you for all your help!
I think , This line in OnClickListener of floorPlan in your MainActivity causing problem :
startActivity(new Intent("com.example.helloworld3.FLOORPLAN"));
putString method is correct. It's inherited from android.os.BaseBundle.
The logcat shows your bundle get from intent.getExtras() is null:
Bundle myb2= getIntent().getExtras();
roomName2 = myb2.getString("key1");//here myb2 is null
Maybe you should override onNewIntent to setIntent:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
Why you have started activity 2 times in below code ?
Intent a = new Intent(MainActivity.this, FloorPlan.class);
a.putExtras(myb); startActivity(a);
startActivity(new Intent("com.example.helloworld3.FLOORPLAN")); // this intent doesnt`t have bundle
This might be the reason which lead where Bundle object is null in intent and causing nullpointerexception.

NullPointerException on MrNom

I was trying to execute Mr Nom(from the book Begining Android Games by Mario Zechner). but it doesn't work. My first atemp was create 2 different projects, one called framework where are com.badlogic.androidgames.framework and com.badlogic.androidgames.framework files and other project called mrnom (com.badlogic.androidgames.mrnom)with the rest of files. the framework project was added mrnom project/java build path/project/add and the result was this:
logcat
11-07 15:21:55.573: W/dalvikvm(641): Unable to resolve superclass of Lcom/badlogic/androidgames/mrnom/MrNom; (445)
11-07 15:21:55.573: W/dalvikvm(641): Link of class 'Lcom/badlogic/androidgames/mrnom/MrNom;' failed
11-07 15:21:55.573: D/AndroidRuntime(641): Shutting down VM
11-07 15:21:55.573: W/dalvikvm(641): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-07 15:21:55.583: E/AndroidRuntime(641): FATAL EXCEPTION: main
11-07 15:21:55.583: E/AndroidRuntime(641): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.badlogic.androidgames.mrnom/com.badlogic.androidgames.mrnom.MrNom}: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.os.Looper.loop(Looper.java:137)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.reflect.Method.invoke(Method.java:511)
11-07 15:21:55.583: E/AndroidRuntime(641): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-07 15:21:55.583: E/AndroidRuntime(641): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-07 15:21:55.583: E/AndroidRuntime(641): at dalvik.system.NativeStart.main(Native Method)
11-07 15:21:55.583: E/AndroidRuntime(641): Caused by: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:21:55.583: E/AndroidRuntime(641): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-07 15:21:55.583: E/AndroidRuntime(641): ... 11 more
11-07 15:24:06.602: E/Trace(662): error opening trace file: No such file or directory (2)
11-07 15:24:06.902: W/dalvikvm(662): Unable to resolve superclass of Lcom/badlogic/androidgames/mrnom/MrNom; (445)
11-07 15:24:06.902: W/dalvikvm(662): Link of class 'Lcom/badlogic/androidgames/mrnom/MrNom;' failed
11-07 15:24:06.902: D/AndroidRuntime(662): Shutting down VM
11-07 15:24:06.932: W/dalvikvm(662): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-07 15:24:06.952: E/AndroidRuntime(662): FATAL EXCEPTION: main
11-07 15:24:06.952: E/AndroidRuntime(662): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.badlogic.androidgames.mrnom/com.badlogic.androidgames.mrnom.MrNom}: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.os.Looper.loop(Looper.java:137)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.reflect.Method.invoke(Method.java:511)
11-07 15:24:06.952: E/AndroidRuntime(662): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-07 15:24:06.952: E/AndroidRuntime(662): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-07 15:24:06.952: E/AndroidRuntime(662): at dalvik.system.NativeStart.main(Native Method)
11-07 15:24:06.952: E/AndroidRuntime(662): Caused by: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:24:06.952: E/AndroidRuntime(662): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-07 15:24:06.952: E/AndroidRuntime(662): ... 11 more
later I removed the framework from mrnom and added it using a jar file, the result was the same
Now, I copy the com.badlogic.androidgames.framework and com.badlogic.androidgames.framework files into mr project then I have com.badlogic.androidgames.mrnom, com.badlogic.androidgames.framework and com.badlogic.androidgames.framework in the same project but now the error is
logcat
12-05 15:42:43.510: D/dalvikvm(582): GC_EXTERNAL_ALLOC freed 57K, 53% free 2569K/5379K, external 1925K/2137K, paused 239ms
12-05 15:42:43.860: D/dalvikvm(582): GC_EXTERNAL_ALLOC freed 3K, 53% free 2569K/5379K, external 2515K/2701K, paused 36ms
12-05 15:42:44.100: W/dalvikvm(582): threadid=11: thread exiting with uncaught exception (group=0x40015560)
12-05 15:42:44.100: E/AndroidRuntime(582): FATAL EXCEPTION: Thread-12
12-05 15:42:44.100: E/AndroidRuntime(582): java.lang.NullPointerException
12-05 15:42:44.100: E/AndroidRuntime(582): at com.badlogic.androidgames.mrnom.Settings.load(Settings.java:18)
12-05 15:42:44.100: E/AndroidRuntime(582): at com.badlogic.androidgames.mrnom.LoadingScreen.update(LoadingScreen.java:41)
12-05 15:42:44.100: E/AndroidRuntime(582): at com.badlogic.androidgames.framework.impl.AndroidFastRenderView.run(AndroidFastRenderView.java:36)
12-05 15:42:44.100: E/AndroidRuntime(582): at java.lang.Thread.run(Thread.java:1019)
Settings
package com.badlogic.androidgames.mrnom;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import com.balogic.androidgames.framework.FileIO;
public class Settings {
public static boolean soundEnable=true;
public static int[] highscores=new int[]{100,80,50,30,10};
public static void load(FileIO files){
BufferedReader in=null;
try{
in=new BufferedReader(new InputStreamReader(files.readFile(".mrnom")));// line 18 error here
soundEnable=Boolean.parseBoolean(in.readLine());
for(int i=0; i<5;i++){
highscores[i]=Integer.parseInt(in.readLine());
}
}catch(IOException e){
// :( vale,trabajamos con valores predeterminados
}catch(NumberFormatException e){
// :/ vale, estos valores nos han salvado el día
}finally{
try{
if(in!=null)
in.close();
}catch(IOException e){
//nada
}
}
}
public static void save(FileIO files){
BufferedWriter out=null;
try{
out=new BufferedWriter(new OutputStreamWriter(files.writeFile(".mrnom")));
out.write(Boolean.toString(soundEnable));
for(int i=0; i<5; i++){
out.write(Integer.toString(highscores[i]));
}
}catch(IOException e){
//nada
}finally{
try{
if(out!=null)
out.close();
}catch(IOException e){
//nada
}
}
}
public static void addScore(int score){
for(int i=0;i<5;i++){
if(highscores[i]<score){
for(int j=4;j>i;j--)
highscores[j]=highscores[j-1];
highscores[i]=score;
break;
}
}
}
}
Loadingsceen
package com.badlogic.androidgames.mrnom;
import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Graphics;
import com.badlogic.androidgames.framework.Graphics.PixmapFormat;
import com.badlogic.androidgames.framework.Screen;
public class LoadingScreen extends Screen{
public LoadingScreen(Game game){
super(game);
}
#Override
public void update(float deltaTime){
Graphics g=game.getGraphics();
Assets.background = g.newPixmap("background.png", PixmapFormat.RGB565);
Assets.logo = g.newPixmap("logo.png", PixmapFormat.ARGB4444);
Assets.mainMenu = g.newPixmap("mainmenu.png", PixmapFormat.ARGB4444);
Assets.buttons = g.newPixmap("buttons.png", PixmapFormat.ARGB4444);
Assets.help1 = g.newPixmap("help1.png", PixmapFormat.ARGB4444);
Assets.help2 = g.newPixmap("help2.png", PixmapFormat.ARGB4444);
Assets.help3 = g.newPixmap("help3.png", PixmapFormat.ARGB4444);
Assets.numbers = g.newPixmap("numbers.png", PixmapFormat.ARGB4444);
Assets.ready = g.newPixmap("ready.png", PixmapFormat.ARGB4444);
Assets.pause = g.newPixmap("pausemenu.png", PixmapFormat.ARGB4444);
Assets.gameOver = g.newPixmap("gameover.png", PixmapFormat.ARGB4444);
Assets.headUp = g.newPixmap("headup.png", PixmapFormat.ARGB4444);
Assets.headLeft = g.newPixmap("headleft.png", PixmapFormat.ARGB4444);
Assets.headDown = g.newPixmap("headdown.png", PixmapFormat.ARGB4444);
Assets.headRight = g.newPixmap("headright.png", PixmapFormat.ARGB4444);
Assets.tail = g.newPixmap("tail.png", PixmapFormat.ARGB4444);
Assets.stain1 = g.newPixmap("stain.png", PixmapFormat.ARGB4444);
Assets.stain2 = g.newPixmap("stain2.png", PixmapFormat.ARGB4444);
Assets.stain3 = g.newPixmap("stain3.png", PixmapFormat.ARGB4444);
Assets.click = game.getAudio().newSound("click.ogg");
Assets.eat = game.getAudio().newSound("eat.ogg");
Assets.bitten = game.getAudio().newSound("bitten.ogg");
Settings.load(game.getFileIO()); //line 41 error here
game.setScreen(new MainMenuScreen(game));
}
#Override
public void present(float deltaTime) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}
AndroidFastRenderView
package com.badlogic.androidgames.framework.impl;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class AndroidFastRenderView extends SurfaceView implements Runnable{
AndroidGame game;
Bitmap framebuffer;
Thread renderThread=null;
SurfaceHolder holder;
volatile boolean running=false;
public AndroidFastRenderView(AndroidGame game,Bitmap framebuffer){
super(game);
this.game=game;
this.framebuffer=framebuffer;
this.holder=getHolder();
}
public void resume(){
running=true;
renderThread=new Thread(this);
renderThread.start();
}
public void run(){
Rect dstRect=new Rect();
long startTime=System.nanoTime();
while(running){
if(!holder.getSurface().isValid())
continue;
float deltaTime=(System.nanoTime()-startTime)/1000000000.0f;
startTime=System.nanoTime();
game.getCurrentScreen().update(deltaTime);//line 36 error here
game.getCurrentScreen().present(deltaTime);
Canvas canvas=holder.lockCanvas();
canvas.getClipBounds(dstRect);
canvas.drawBitmap(framebuffer, null, dstRect,null);
holder.unlockCanvasAndPost(canvas);
}
}
public void pause(){
running=false;
while(true){
try{
renderThread.join();
break;
}catch(InterruptedException e){
//vuelve a intentarlo
}
}
}
}
Eclipse doesn't showme any mistake on code but on the emulator just say "Sorry! the application mrnom (process com.badlogic.androidgames.mrnom) has stopped unexpectedly. Please try again"
Can you help me with this? No idea what's happening :( Thank you so much.

Email App is not working on real device [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I have a simple android one button app that send automatic email when the button is pressed. The app works fine in emulator but on real device (samsung gt-n7000) the app won't work. The device is connected to wi-fi only.
here are the codes:
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class GMailSender extends javax.mail.Authenticator {
private String _user;
private String _pass;
private String[] _to;
private String _from;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public GMailSender() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public GMailSender(String user, String pass) {
this();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
#Override
public javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(_user,_pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if(_debuggable) {
props.put("mail.debug", "true");
}
if(_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
this._body = _body;
}
public String[] get_to() {
return _to;
}
public void set_to(String[] _to) {
this._to = _to;
}
public String get_from() {
return _from;
}
public void set_from(String _from) {
this._from = _from;
}
public String get_subject() {
return _subject;
}
public void set_subject(String _subject) {
this._subject = _subject;
}
}
MainClass:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sending(View v) {
GMailSender mailsender = new GMailSender("example#gmail.com", "password");
String[] toArr = { "mussa2kasssim#hotmail.com" };
mailsender.set_to(toArr);
mailsender.set_from("example#gmail.com");
mailsender.set_subject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
mailsender.setBody("Hello World!");
// mailsender.send();
try {
//mailsender.addAttachment("/sdcard/filelocation");
if (mailsender.send()) {
Toast.makeText(MainActivity.this,
"Email was sent successfully.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Email was not sent.",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("MailApp", "Could not send email", e);
}
}
}
NB: "example#gmail.com" and "password" are replaced with authentic values.
Please help. Thank you
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nikhil.emailing"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.emailing.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.emailing.EmailActivity"
android:label="#string/title_activity_email" >
</activity>
</application>
</manifest>
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="sending"
android:text="Email" />
</RelativeLayout>
Error Log:
11-07 12:43:07.616: ERROR/lights(1845): write_int: path/sys/devices/virtual/sec/sec_touchkey/brightness, value 1
11-07 12:43:07.841: ERROR/MailApp(24559): Could not send email
11-07 12:43:07.841: ERROR/MailApp(24559): android.os.NetworkOnMainThreadException
11-07 12:43:07.841: ERROR/MailApp(24559): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
11-07 12:43:07.841: ERROR/MailApp(24559): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
11-07 12:43:07.841: ERROR/MailApp(24559): at java.net.InetAddress.getLocalHost(InetAddress.java:371)
11-07 12:43:07.841: ERROR/MailApp(24559): at javax.mail.internet.InternetAddress.getLocalAddress(InternetAddress.java:517)
11-07 12:43:07.841: ERROR/MailApp(24559): at javax.mail.internet.UniqueValue.getUniqueMessageIDValue(UniqueValue.java:99)
11-07 12:43:07.841: ERROR/MailApp(24559): at javax.mail.internet.MimeMessage.updateMessageID(MimeMessage.java:2054)
11-07 12:43:07.841: ERROR/MailApp(24559): at javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2076)
11-07 12:43:07.841: ERROR/MailApp(24559): at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2042)
11-07 12:43:07.841: ERROR/MailApp(24559): at javax.mail.Transport.send(Transport.java:117)
11-07 12:43:07.841: ERROR/MailApp(24559): at com.nikhil.emailing.GMailSender.send(GMailSender.java:105)
11-07 12:43:07.841: ERROR/MailApp(24559): at com.nikhil.emailing.MainActivity.sending(MainActivity.java:31)
11-07 12:43:07.841: ERROR/MailApp(24559): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 12:43:07.841: ERROR/MailApp(24559): at java.lang.reflect.Method.invoke(Method.java:511)
11-07 12:43:07.841: ERROR/MailApp(24559): at android.view.View$1.onClick(View.java:3095)
11-07 12:43:07.841: ERROR/MailApp(24559): at android.view.View.performClick(View.java:3627)
11-07 12:43:07.841: ERROR/MailApp(24559): at android.view.View$PerformClick.run(View.java:14329)
11-07 12:43:07.841: ERROR/MailApp(24559): at android.os.Handler.handleCallback(Handler.java:605)
11-07 12:43:07.841: ERROR/MailApp(24559): at android.os.Handler.dispatchMessage(Handler.java:92)
11-07 12:43:07.841: ERROR/MailApp(24559): at android.os.Looper.loop(Looper.java:137)
11-07 12:43:07.841: ERROR/MailApp(24559): at android.app.ActivityThread.main(ActivityThread.java:4511)
11-07 12:43:07.841: ERROR/MailApp(24559): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 12:43:07.841: ERROR/MailApp(24559): at java.lang.reflect.Method.invoke(Method.java:511)
11-07 12:43:07.841: ERROR/MailApp(24559): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
11-07 12:43:07.841: ERROR/MailApp(24559): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
11-07 12:43:07.841: ERROR/MailApp(24559): at dalvik.system.NativeStart.main(Native Method)
11-07 12:43:08.786: ERROR/DataRouter(1690): usb connection is true
11-07 12:43:08.786: ERROR/DataRouter(1690): DSR is ON. Don't send DTR ON.
11-07 12:43:09.121: ERROR/lights(1845): write_int: path /sys/devices/virtual/sec/sec_touchkey/brightness, value 2
11-07 12:43:09.741: ERROR/AlarmManagerService(1845): android_server_AlarmManagerService_set to type=1, 1383830133.779000000
11-07 12:43:09.896: ERROR/AlarmManagerService(1845): android_server_AlarmManagerService_set to type=1, 1383828192.898000000
11-07 12:43:10.791: ERROR/DataRouter(1690): usb connection is true
11-07 12:43:10.791: ERROR/DataRouter(1690): DSR is ON. Don't send DTR ON.
11-07 12:43:12.791: ERROR/DataRouter(1690): usb connection is true
11-07 12:43:12.791: ERROR/DataRouter(1690): DSR is ON. Don't send DTR ON.
11-07 12:43:12.896: ERROR/AlarmManagerService(1845): android_server_AlarmManagerService_set to type=1, 1383830133.779000000
11-07 12:43:13.036: ERROR/AlarmManagerService(1845): android_server_AlarmManagerService_set to type=1, 1383828196.040000000
The exception says android.os.NetworkOnMainThreadException
That means network related tasks should not be performed on main thread (UI thread specifically).
Run it on background thread and it will work.
The related task should be performed in AsyncTask.
It has to do with some ThreadPolicy, I read it from another post. It basically blocks connection that the app initiates. So to disable this policy, I had to put this piece of code in onCreate() of the activity using the connection.
The code is:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And it works as expected :))

Android nullPointerException error

Eclipse finds no errors in my code, but when I try to run the app on an emulator, it opens and then immediately crashes. Logcat gives me the vague nullPointerException error. I can comment out the onKeyDown method, and then it runs just fine. But of course, I can't use the back key to go back, it will just close out the app.
My code is as follows:
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class MainActivity extends Activity {
static String[] items = {"Campaign", "Multiplayer", "Zombies"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
final ViewFlipper viewflipper = (ViewFlipper) findViewById(R.id.viewflipper1);
listView.setAdapter(new BaseAdapter(){
public int getCount() {
return items.length;
}
public Object getItem(int position) {
return items[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_row, null);
TextView textView = (TextView) view.findViewById(R.id.TextView01);
textView.setText(items[position]);
textView.setTextColor(Color.rgb(255,106,0));
textView.setTextSize(24);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setTextColor(Color.rgb(255,106,0));
return view;
}});
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (position == 0) {
viewflipper.showNext();
}if (position == 1) {
viewflipper.showNext();
viewflipper.showNext();
}if (position == 2) {
viewflipper.showNext();
viewflipper.showNext();
viewflipper.showNext();
}}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
ViewFlipper viewflipper = (ViewFlipper) findViewById(R.id.viewflipper1);
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if(viewflipper.getDisplayedChild() == 0){
viewflipper.showPrevious();
}if(viewflipper.getDisplayedChild() == 1){
viewflipper.showPrevious();
viewflipper.showPrevious();
}if(viewflipper.getDisplayedChild() == 2){
viewflipper.showPrevious();
viewflipper.showPrevious();
viewflipper.showPrevious();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
};
My Logcat is as follows:
01-21 11:38:46.151: E/AndroidRuntime(760): FATAL EXCEPTION: main
01-21 11:38:46.151: E/AndroidRuntime(760): java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.blackopsiiexperience/com.example.blackopsiiexperience.MainActivity}: java.lang.NullPointerException
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.os.Handler.dispatchMessage(Handler.java:99)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.os.Looper.loop(Looper.java:137)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-21 11:38:46.151: E/AndroidRuntime(760): at java.lang.reflect.Method.invokeNative(Native Method)
01-21 11:38:46.151: E/AndroidRuntime(760): at java.lang.reflect.Method.invoke(Method.java:511)
01-21 11:38:46.151: E/AndroidRuntime(760): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-21 11:38:46.151: E/AndroidRuntime(760): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-21 11:38:46.151: E/AndroidRuntime(760): at dalvik.system.NativeStart.main(Native Method)
01-21 11:38:46.151: E/AndroidRuntime(760): Caused by: java.lang.NullPointerException
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.Activity.findViewById(Activity.java:1839)
01-21 11:38:46.151: E/AndroidRuntime(760): at com.example.blackopsiiexperience.MainActivity.<init>(MainActivity.java:73)
01-21 11:38:46.151: E/AndroidRuntime(760): at java.lang.Class.newInstanceImpl(Native Method)
01-21 11:38:46.151: E/AndroidRuntime(760): at java.lang.Class.newInstance(Class.java:1319)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
01-21 11:38:46.151: E/AndroidRuntime(760): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
01-21 11:38:46.151: E/AndroidRuntime(760): ... 11 more
Any suggestions?
move
ViewFlipper viewflipper = (ViewFlipper) findViewById(R.id.viewflipper1);
inside onCreate of Activity after setting layout for Activity
EDIT :
declare Viewflipper as class level field to access it through out class instead of method level as :
public class MainActivity extends Activity {
static String[] items = {"Campaign", "Multiplayer", "Zombies"};
ListView listView;
ViewFlipper viewflipper; //<<<< declare here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
viewflipper = (ViewFlipper) findViewById(R.id.viewflipper1);
//your code here.....

Categories