Unable to insert documents into mongodb database gives NetworkOnMainthread EXception - java

Im making an android app to fetch data from user and store it in a mongodb database
mongodb runs on localhost:27017 and im able to connect to it using 10.0.3.2:27017 on genymotion emulator
here is LoginActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends AppCompatActivity {
static DB db;
static DBCollection locations;
public String name,middlename,surname,userid,profilelink,imageUrl,emailid,gender,birthday;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
nextActivity(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("JSON",response.toString());
try {
emailid=object.getString("email");
gender=object.getString("gender");
birthday=object.getString("birthday");
TextView nameView6 = (TextView)findViewById(R.id.emailr);
nameView6.setText(emailid);
TextView nameView7 = (TextView)findViewById(R.id.genderr);
nameView7.setText(gender);
TextView nameView8 = (TextView)findViewById(R.id.birthdayr);
nameView8.setText(birthday);
String[] dset={emailid,gender,birthday};
yalla(dset);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
loginButton.setReadPermissions("user_friends");
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
loginButton.setReadPermissions("user_birthday");
loginButton.registerCallback(callbackManager, callback);
}
#Override
protected void onResume() {
super.onResume();
//Facebook login
Profile profile = Profile.getCurrentProfile();
nextActivity(profile);
}
#Override
protected void onPause() {
super.onPause();
}
protected void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
private void nextActivity(Profile profile){
if(profile != null){
Intent main = new Intent(LoginActivity.this, MainActivity.class);
main.putExtra("name", profile.getFirstName());
main.putExtra("middlename", profile.getMiddleName());
main.putExtra("surname", profile.getLastName());
main.putExtra("userid", profile.getId());
main.putExtra("profilelink", profile.getLinkUri());
main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
startActivity(main);
}
}
public static void yalla(String[] args){
String[] dset;
dset=args;
//try {
String uri = "mongodb://10.0.3.2:27017";
Log.v("enterhere", dset[0]);
MongoClientURI mongoClientURI=new MongoClientURI(uri);
//MongoClient mongoClient = new MongoClient("mongodb://10.0.3.2:27017/test");
Log.v("connectedserver", dset[0]);
MongoClient mongoClient = new MongoClient(mongoClientURI);
MongoDatabase database = mongoClient.getDatabase("users");
Log.v("Connect to database successfully",database.getName());
MongoCollection mongoCollection = database.getCollection("assest");
Log.v("collection", dset[0]);
Document doc = new Document("emailid", dset[0])
.append("gender", dset[1])
.append("birthday", dset[2]);
Log.v("document update", dset[0]);
mongoCollection.insertOne(doc);
Log.v("doc insertion", dset[0]);
mongoClient.close();
//} catch (MongoException e)
//{
// e.getStackTrace();
//}
}
}
Error on android studio
V/document update: zissujith#gmail.com
I/cluster: No server chosen by PrimaryServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=10.0.3.2:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
I/connection: Opened connection [connectionId{localValue:1, serverValue:17}] to 10.0.3.2:27017
I/cluster: Monitor thread successfully connected to server with description ServerDescription{address=10.0.3.2:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 0, 14]}, minWireVersion=0, maxWireVersion=3, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=9233253}
D/dalvikvm: GC_CONCURRENT freed 413K, 5% free 12382K/12935K, paused 11ms+1ms, total 17ms
I/connection: Closed connection [connectionId{localValue:2}] to 10.0.3.2:27017 because the underlying connection was closed.
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa62fe288)
E/AndroidRuntime: FATAL EXCEPTION: main
com.mongodb.MongoException: android.os.NetworkOnMainThreadException
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:125)
at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46)
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:366)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:94)
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:80)
at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:69)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:184)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:177)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:141)
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:72)
at com.mongodb.Mongo.execute(Mongo.java:747)
at com.mongodb.Mongo$2.execute(Mongo.java:730)
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:482)
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:277)
at com.sujithsizon.lzlogin3.LoginActivity.yalla(LoginActivity.java:224)
at com.sujithsizon.lzlogin3.LoginActivity$3$1.onCompleted(LoginActivity.java:99)
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:304)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1368)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:144)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:842)
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46) 
at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:366) 
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:94) 
at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:80) 
at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:69) 
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86) 
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:184) 
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:177) 
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:141) 
at com.mongodb.operation.MixedBulkWriteOperation.execute(MixedBulkWriteOperation.java:72) 
at com.mongodb.Mongo.execute(Mongo.java:747) 
at com.mongodb.Mongo$2.execute(Mongo.java:730) 
at com.mongodb.MongoCollectionImpl.executeSingleWriteRequest(MongoCollectionImpl.java:482) 
at com.mongodb.MongoCollectionImpl.insertOne(MongoCollectionImpl.java:277) 
at com.sujithsizon.lzlogin3.LoginActivity.yalla(LoginActivity.java:224) 
at com.sujithsizon.lzlogin3.LoginActivity$3$1.onCompleted(LoginActivity.java:99) 
at com.facebook.GraphRequest$1.onCompleted(GraphRequest.java:304) 
at com.facebook.GraphRequest$5.run(GraphRequest.java:1368) 
at android.os.Handler.handleCallback(Handler.java:615) 
at android.os.Handler.dispatchMessage(Handler.java:92) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 

You can use Async Task for this. I don't know much about mongoDB, but assuming your yalla method has heavy network operation which includes mongoDB.
Try to add yalla method into new AyancTask.
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//Include your mongoDB accessing method here, in background thread.
}
}
And you can execute this method by the following line from your activity.
new DownloadFilesTask().execute(url1, url2, url3);
Hope this helps.
EDIT: Now you are including your method in AsyncTask, and passing URL as arguments, Just provide the links via execute() method. No need to use this String[] = args, which currently you are using in your methos.
For more details on AsyncTask, refer the official docs from this link :)

I am actually trying to do the same and found mongoclient won't work so I used the common class to connect to my server on mlab then I used an asynkTask inner class with HTTPUrlConnection to get the data I stored, check out this link for querying urls for mlab-> http://docs.mlab.com/data-api/
Also check this out-> https://m.youtube.com/watch?v=RSZ2pyhfR0I
public class Common {
private static String DB_NAME = "edmtdev";
private static String COLLECTION_NAME = "user";
public static String API_KEY = "YOUR API KEY";
public static String getAddressSingle(User user) {
String baseUrl = String.format("https://api.mlab.com/api/1/databases/%s/collections/%s", DB_NAME, COLLECTION_NAME);
StringBuilder stringBuilder = new StringBuilder(baseUrl);
stringBuilder.append("/"+user.get_id().getOid()+"?apiKey="+API_KEY);
return stringBuilder.toString():
}

Related

java.lang.RuntimeException: An error occurred while executing doInBackground() Singleton android error

Ihave a problem in sending image from and Android application to API . I am getting "java.lang.RuntimeException: An error occurred while executing doInBackground()" error. Please advice me on what to do. Thanks.
RecognizeConceptsActivity.java
package com.example.statistic.api.v2.activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import com.example.statistic.R;
import com.example.statistic.api.v2.App;
import com.example.statistic.api.v2.ClarifaiUtil;
import com.example.statistic.api.v2.adapter.RecognizeConceptsAdapter;
import java.util.Collections;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import clarifai2.api.ClarifaiResponse;
import clarifai2.dto.input.ClarifaiImage;
import clarifai2.dto.input.ClarifaiInput;
import clarifai2.dto.model.ConceptModel;
import clarifai2.dto.model.output.ClarifaiOutput;
import clarifai2.dto.prediction.Concept;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
public final class RecognizeConceptsActivity extends BaseActivity {
public static final int PICK_IMAGE = 100;
// the list of results that were returned from the API
#BindView(R.id.resultsList)
RecyclerView resultsList;
// the view where the image the user selected is displayed
#BindView(R.id.image2)
ImageView imageView;
// switches between the text prompting the user to hit the FAB, and the loading spinner
#BindView(R.id.switcher)
ViewSwitcher switcher;
// the FAB that the user clicks to select an image
#BindView(R.id.fab)
View fab;
#NonNull
private final RecognizeConceptsAdapter adapter = new RecognizeConceptsAdapter();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
resultsList.setLayoutManager(new LinearLayoutManager(this));
resultsList.setAdapter(adapter);
}
#OnClick(R.id.fab)
void pickImage() {
startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"), PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch(requestCode) {
case PICK_IMAGE:
final byte[] imageBytes = ClarifaiUtil.retrieveSelectedImage(this, data);
if (imageBytes != null) {
onImagePicked(imageBytes);
}
break;
}
}
private void onImagePicked(#NonNull final byte[] imageBytes) {
// Now we will upload our image to the Clarifai API
setBusy(true);
// Make sure we don't show a list of old concepts while the image is being uploaded
adapter.setData(Collections.<Concept>emptyList());
new AsyncTask<Void, Void, ClarifaiResponse<List<ClarifaiOutput<Concept>>>>() {
#Override
protected ClarifaiResponse<List<ClarifaiOutput<Concept>>> doInBackground(Void... params) {
// The default Clarifai model that identifies concepts in images
final ConceptModel generalModel = App.get().clarifaiClient().getDefaultModels().generalModel();
// Use this model to predict, with the image that the user just selected as the input
return generalModel.predict()
.withInputs(ClarifaiInput.forImage(ClarifaiImage.of(imageBytes)))
.executeSync();
}
#Override
protected void onPostExecute(ClarifaiResponse<List<ClarifaiOutput<Concept>>> response) {
setBusy(false);
if (!response.isSuccessful()) {
showErrorSnackbar(R.string.error_while_contacting_api);
return;
}
final List<ClarifaiOutput<Concept>> predictions = response.get();
if (predictions.isEmpty()) {
showErrorSnackbar(R.string.no_results_from_api);
return;
}
adapter.setData(predictions.get(0).data());
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length));
}
private void showErrorSnackbar(#StringRes int errorString) {
Snackbar.make(
root,
errorString,
Snackbar.LENGTH_INDEFINITE
).show();
}
}.execute();
}
#Override
protected int layoutRes() { return R.layout.activity_recognize; }
private void setBusy(final boolean busy) {
runOnUiThread(new Runnable() {
#Override
public void run() {
switcher.setDisplayedChild(busy ? 1 : 0);
imageView.setVisibility(busy ? GONE : VISIBLE);
fab.setEnabled(!busy);
}
});
}
}
App.java
public class App extends Application {
// In a real app, rather than attaching singletons (such as the API client instance) to your Application instance,
// it's recommended that you use something like Dagger 2, and inject your client instance.
// Since that would be a distraction here, we will just use a regular singleton.
private static App INSTANCE;
#NonNull
public static App get() {
final App instance = INSTANCE;
if (instance == null) {
throw new IllegalStateException("App has not been created yet!");
}
return instance;
}
#Nullable
private ClarifaiClient client;
#Override
public void onCreate() {
INSTANCE = this;
client = new ClarifaiBuilder(getString(R.string.clarifai_api_key))
// Optionally customize HTTP client via a custom OkHttp instance
.client(new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS) // Increase timeout for poor mobile networks
// Log all incoming and outgoing data
// NOTE: You will not want to use the BODY log-level in production, as it will leak your API request details
// to the (publicly-viewable) Android log
.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
#Override
public void log(String logString) {
Timber.e(logString);
}
}).setLevel(HttpLoggingInterceptor.Level.BODY))
.build()
)
.buildSync(); // use build() instead to get a Future<ClarifaiClient>, if you don't want to block this thread
super.onCreate();
// Initialize our logging
Timber.plant(new Timber.DebugTree());
}
#NonNull
public ClarifaiClient clarifaiClient() {
final ClarifaiClient client = this.client;
if (client == null) {
throw new IllegalStateException("Cannot use Clarifai client before initialized");
}
return client;
}
}
This is the logcat error
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.statistic, PID: 3451
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:325)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.IllegalStateException: App has not been created yet!
at com.example.statistic.api.v2.App.get(App.java:28)
at com.example.statistic.api.v2.activity.RecognizeConceptsActivity$1.doInBackground(RecognizeConceptsActivity.java:105)
at com.example.statistic.api.v2.activity.RecognizeConceptsActivity$1.doInBackground(RecognizeConceptsActivity.java:101)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
Please advice me on what to do. Thanks

Android- Null pointer exception from getStringExtra using intent send a value to another activity by button click

I am facing the problem when I use Intent to send a value to another activity by click a button. I have tried to solve it in many ways but it always show NullPointerException although I declared it clearly.
Here is my code.
Manufacturer.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class Manufacturer extends AppCompatActivity {
public String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manufacturer);
Button toyota = (Button) findViewById(R.id.Toyota);
Button subaru = (Button) findViewById(R.id.Subaru);
Button audi = (Button) findViewById(R.id.Audi);
toyota.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Toyota";
goAnother(message.toString());
}
});
subaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Subaru";
goAnother(message);
}
});
audi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = "Audi";
goAnother(message);
}
});
}
protected void goAnother(String brand){
Intent i = new Intent(Manufacturer.this, ShowCarPrice.class);
i.putExtra("brand", brand);
startActivity(i);
}
}
Showcarprice.java
package com.example.student.macheckcar;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.Window;
import java.util.ArrayList;
public class ShowCarPrice extends AppCompatActivity {
private Cursor cursor;
private ArrayList<String> price;
private ArrayAdapter<String> aa;
private DBprice dbPrice;
private Manufacturer maFact;
SQLiteDatabase db;
ListView list;
Intent intent = getIntent();
String brand = intent.getStringExtra("brand");
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_car_price);
list = (ListView) findViewById(R.id.listView);
dbPrice = new DBprice(this);
db = dbPrice.getWritableDatabase();
cursor = db.rawQuery("SELECT " + dbPrice.KEY_TASK + " FROM " + dbPrice.TABLE_NAME + " WHERE Manufacturer = ?", new String[] {brand});
price = new ArrayList<String>();
cursor.moveToFirst();
while ( !cursor.isAfterLast() ){
price.add(cursor.getString(cursor.getColumnIndex(dbPrice.KEY_TASK)));
cursor.moveToNext();
}
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, price);
list.setAdapter(aa);
}
public void onPause() {
super.onPause();
dbPrice.close();
db.close();
}
}
And the error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student.macheckcar, PID: 934
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.student.macheckcar/com.example.student.macheckcar.ShowCarPrice}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.student.macheckcar.ShowCarPrice.<init>(ShowCarPrice.java:22)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5001) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
at dalvik.system.NativeStart.main(Native Method) 
Please help.
UPDATE
public class ShowCarPrice extends AppCompatActivity {
// OK, Create the objects, variables here if needed
Intent intent;
String brand;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout);
// You should assign the intent here (in onCreate method)
intent = getIntent();
// Then, the string variable
brand = intent.getStringExtra("brand");
// You can also check whether or not received a valid value
if (brand != null && !brand.isEmpty())
// do something with brand value
else
// brand value is null or empty
}
}
Well, you call getIntent() at the wrong position. You should call getIntent() in method onCreate() , and I don't know why you keep intent as a member of your activity. If I were you I just do
String brand = getIntent().getStringExtra("brand");
in onCreate() method.
get your intent and extras of intent in onCreate() method of activity just check below link for this
https://stackoverflow.com/a/5265952/5316836

how to stop jsonParser.makeHttpRequest in android

I crate app to check the database for login info by using jsonParser.makeHttpRequest
I try to make my app to stop after 10 second in case there is no internet connection or no response from the server. The code work however when the login button click for the second time the app crash
Could anyone please support why this happen
please see the below for the code
package com.example.pfms;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String id,pass,p,logincheck;
private EditText username,password;
private Button login;
private CheckLogin cl;
private ProgressDialog pDialog;
private SharedPreferences prefs;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String url = "http://192.168.1.11/pfm/get_id.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
cl= new CheckLogin();
username=(EditText)findViewById(R.id.editText1);
password=(EditText)findViewById(R.id.editText2);
login=(Button)findViewById(R.id.button1);
prefs = this.getSharedPreferences("com.example.pfms", MODE_PRIVATE);
logincheck=prefs.getString("com.example.pfms.login", "0");
if(!logincheck.equals("0")){
Intent i=new Intent(MainActivity.this,TechOption.class);
Bundle info=new Bundle();
info.putString("techid",logincheck);
i.putExtras(info);
startActivity(i);
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cl.execute();
}
});
}
class CheckLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Checking Login info. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
p="0";
pass="0";
Log.d("test", "dialog");
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
// runOnUiThread(new Runnable() {
// public void run() {
// Check for success tag
int success;
try {
Log.d("test", "run");
// Building Parameters
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
id=username.getText().toString();
pass=password.getText().toString();
params2.add(new BasicNameValuePair("id",id));
// getting product details by making HTTP request
// Note that product details url will use GET request
// HttpParams httpParameters = new BasicHttpParams();
// HttpConnectionParams.setConnectionTimeout(httpParameters, 30000);
// HttpConnectionParams.setSoTimeout(httpParameters, 30000);
// DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
messageHandler.sendEmptyMessageDelayed(0, 10000);
Log.d("test", "before");
JSONObject json = jsonParser.makeHttpRequest(
url, "GET", params2);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
Log.d("test", "before success");
if (success == 1) {
// successfully received product details
JSONArray actiondetail = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject c = actiondetail.getJSONObject(0);
// Storing each json item in variable
p="";
p = c.getString("pass");
Log.d("info", "p="+p);
Log.d("info", "pass="+pass);
}else{
Toast.makeText(getBaseContext(), "Wrong Username", Toast.LENGTH_LONG).show();
}
Log.d("test", "after success");
} catch (JSONException e) {
//pDialog.dismiss();
//Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
// }
// });
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
Log.d("test", "dismiss dailog");
if(p.contentEquals(pass)){
Intent i=new Intent(MainActivity.this,TechOption.class);
Bundle info=new Bundle();
info.putString("techid",id);
i.putExtras(info);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("com.example.pfms.login",id);
editor.commit();
startActivity(i);
}
else{
Toast.makeText(getBaseContext(), "Wrong Password", Toast.LENGTH_LONG).show();
}
}
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
pDialog.dismiss();
Toast.makeText(getBaseContext(), "Please check internet connection", Toast.LENGTH_LONG).show();
cl.cancel(true);
}
};
}
please see the below for Error :
11-05 09:37:09.053: D/AndroidRuntime(1398): Shutting down VM
11-05 09:37:09.053: W/dalvikvm(1398): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-05 09:37:09.123: E/AndroidRuntime(1398): FATAL EXCEPTION: main
11-05 09:37:09.123: E/AndroidRuntime(1398): java.lang.IllegalStateException: Cannot execute task: the task is already running.
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:575)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.AsyncTask.execute(AsyncTask.java:534)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.example.pfms.MainActivity$2.onClick(MainActivity.java:79)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.view.View.performClick(View.java:4240)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.view.View$PerformClick.run(View.java:17721)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Handler.handleCallback(Handler.java:730)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Handler.dispatchMessage(Handler.java:92)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.os.Looper.loop(Looper.java:137)
11-05 09:37:09.123: E/AndroidRuntime(1398): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-05 09:37:09.123: E/AndroidRuntime(1398): at java.lang.reflect.Method.invokeNative(Native Method)
11-05 09:37:09.123: E/AndroidRuntime(1398): at java.lang.reflect.Method.invoke(Method.java:525)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-05 09:37:09.123: E/AndroidRuntime(1398): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-05 09:37:09.123: E/AndroidRuntime(1398): at dalvik.system.NativeStart.main(Native Method)
An object of an AsyncTask can be run only once. That is why you are getting the IllegalStateException.
Remove the object instantiation [cl= new CheckLogin()] from onCreate().
And instead,
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new CheckLogin.execute(); // creating an anonymous object of the AsyncTask makes sure that you never use it again which prevents any IllegalStateExceptions
}
});

android ui hangs while writting to a bluetooth device from an activity

I am new to android + bluetooth. I am trying to write a simple rfcomm client app which talks to a rfcomm server running on a embedded platfrom. When my application starts it show a listview of paired devices and on clicking one of thoes devices it jumps to a second activity. In this activity I opens a bluetooth socket and connects to it. As soon as I jump to a new activity my UI sort of hangs. This new activity has two buttons. Onclick of these buttons I send data to bluetooth server. But my UI kind of hangs in this activity, once I click a button it takes ages to respond and it generates a error message.
My codes looks like this:
package com.example.bluetoothapp2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
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.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
public int REQUEST_ENABLE_BT = 1;// Just defining a flag
//Define a local bluetooth adapter variable to get id of default Adapter
public BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//Adapter for LIST ITEMS FOR PAIRED DEVICES
public ArrayAdapter<String> mPairedDevicesArrayAdapter;
//Array to store list data for paired device
ArrayList<String> itemPairedArray = new ArrayList<String> ();
//Adapter for LIST ITEMS FOR NEW DEVICES
public ArrayAdapter<String> mNewDevicesArrayAdapter;
//Array to store list data for paired device
ArrayList<String> itemNewDvcArray = new ArrayList<String> ();
//RECORDING HOW MUCH TIMES BUTTON WAS CLICKED
int clickCounter=0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init()
{
//GetListId from Layout
ListView pairedListView = (ListView) findViewById(R.id.listPairedDvc);
ListView newListView = (ListView) findViewById(R.id.listAvailableDvc);
//Bind the list with listview in layout
mPairedDevicesArrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,itemPairedArray);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,itemNewDvcArray);
//Set the adapter to list view (bind a adapter to listview in layout)
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
newListView.setAdapter(mNewDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0)
{
/*findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);*/
for (BluetoothDevice device : pairedDevices)
{
itemPairedArray.add(device.getName() + " => "+ device.getAddress());
}
}
else
{
itemPairedArray.add("noDevices");
}
//Check if device has bluetooth
if(mBluetoothAdapter == null)
{
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
//Check if it is enabled or not
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v)
{
//itemPairedArray.add("Clicked : "+clickCounter++); //Just for debugging
//itemNewDvcArray.add("Clicked : "+clickCounter++); //Just for debugging
//itemNewDvcArray.add("NoDevice");
startDiscovery() ;
//mPairedDevicesArrayAdapter.notifyDataSetChanged();
mNewDevicesArrayAdapter.notifyDataSetChanged();
}
//method to start discovery
private void startDiscovery()
{
// TODO Auto-generated method stub
// If we're already discovering, stop it
if (mBluetoothAdapter.isDiscovering())
{
mBluetoothAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBluetoothAdapter.startDiscovery();
}
protected void onDestroy()
{
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{
// Add the name and address to an array adapter to show in a ListView
itemNewDvcArray.add(device.getName() +" => "+ device.getAddress());
}
}
}
};
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
//Toast.makeText(getApplicationContext(), address, 0).show();
// Create the result Intent and include the MAC address
Intent intent = new Intent(MainActivity.this,ConnectActivity.class);
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
startActivity(intent);
}
};
}
package com.example.bluetoothapp2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ConnectActivity extends Activity {
// Unique UUID for this application
public static final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String address;
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
public BluetoothSocket mmSocket;
public InputStream mmInStream;
public OutputStream mmOutStream;
String tag = "debugging";
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg)
{
// TODO Auto-generated method stub
Log.i(tag, "in handler");
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// DO something
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
//Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
//Toast.makeText(getApplicationContext(), string, 0).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
// Get the message from the intent
Intent intent = getIntent();
address = intent.getStringExtra(MainActivity.EXTRA_DEVICE_ADDRESS);
// Create the text view
TextView textView = (TextView)findViewById(R.id.addrs);
//textView.setTextSize(40);
textView.setText(address);
connect();
}
//method to start discovery
public void connect()
{
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
//Toast.makeText(getApplicationContext(),"connecting", 0).show();
ConnectThread connect = new ConnectThread(device) ;
connect.start();
}
//Thread for establising a connection
private class ConnectThread extends Thread
{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device)
{
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID_INSECURE);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run()
{
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel()
{
try
{
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread
{
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer ; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
//a delay of 20ms occurs after each flush...
mmOutStream.write(bytes);
mmOutStream.flush();
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
//method to start discovery
public void ledOn(View v ) throws IOException
{
//Toast.makeText(getApplicationContext(),"LED ON", 0).show();
mmOutStream.write('o');
}
//method to start discovery
public void ledOff(View v ) throws IOException
{
//Toast.makeText(getApplicationContext(),"LED OFF", 0).show();
mmOutStream.write('f');
}
public void disconnectCntn(View v ) throws IOException
{
String msg = "Disconnect";
mmOutStream.write(msg.getBytes());
// close the connection
mmOutStream.close();
mmInStream.close();
// close the connection
if (mmSocket != null)
try {
mmSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
}
I get following error messages
08-19 13:09:55.833: D/AndroidRuntime(5221): Shutting down VM
08-19 13:09:55.834: W/dalvikvm(5221): threadid=1: thread exiting with uncaught exception (group=0x41cc29a8)
08-19 13:09:55.847: E/AndroidRuntime(5221): FATAL EXCEPTION: main
08-19 13:09:55.847: E/AndroidRuntime(5221): java.lang.IllegalStateException: Could not execute method of the activity
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.view.View$1.onClick(View.java:3606)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.view.View.performClick(View.java:4211)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.view.View$PerformClick.run(View.java:17446)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.os.Handler.handleCallback(Handler.java:725)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.os.Handler.dispatchMessage(Handler.java:92)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.os.Looper.loop(Looper.java:153)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.app.ActivityThread.main(ActivityThread.java:5299)
08-19 13:09:55.847: E/AndroidRuntime(5221): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 13:09:55.847: E/AndroidRuntime(5221): at java.lang.reflect.Method.invoke(Method.java:511)
08-19 13:09:55.847: E/AndroidRuntime(5221): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
08-19 13:09:55.847: E/AndroidRuntime(5221): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
08-19 13:09:55.847: E/AndroidRuntime(5221): at dalvik.system.NativeStart.main(Native Method)
08-19 13:09:55.847: E/AndroidRuntime(5221): Caused by: java.lang.reflect.InvocationTargetException
08-19 13:09:55.847: E/AndroidRuntime(5221): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 13:09:55.847: E/AndroidRuntime(5221): at java.lang.reflect.Method.invoke(Method.java:511)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.view.View$1.onClick(View.java:3601)
08-19 13:09:55.847: E/AndroidRuntime(5221): ... 11 more
08-19 13:09:55.847: E/AndroidRuntime(5221): Caused by: java.io.IOException: [JSR82] write: write() failed.
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.bluetooth.BluetoothSocket.write(BluetoothSocket.java:702)
08-19 13:09:55.847: E/AndroidRuntime(5221): at android.bluetooth.BluetoothOutputStream.write(BluetoothOutputStream.java:56)
08-19 13:09:55.847: E/AndroidRuntime(5221): at com.example.bluetoothapp2.ConnectActivity.ledOn(ConnectActivity.java:213)
08-19 13:09:55.847: E/AndroidRuntime(5221): ... 14 more
Sorry for such a long post. Any idea why is the UI hangs and what could be causing the error.
Thanks
Tama
ConnectedThread is instantiated, however we have skipped the part which starts the thread, fancy calling start() on it? connectedThread.start() which will keep it listening on a socket for any data written.
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
//add this line
connectedThread.start()
//Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());

java.lang.RuntimeException: Unable to start service java.lang.NullPointerException

This is my first app using service. Getting java.lang.RuntimeException: Unable to start service java.lang.NullPointerException. My intention is to send sms when device is in suspend state.
SENDSMS.java
package com.qualcomm.sendsms;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
public class SENDSMS extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sendsms);
String phone_num = null;
String sms = null;
String sleep_time = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
phone_num = extras.getString("Phone_Number");
Log.e("????????????????SEND_SMS", "phno : "+phone_num);
sms = extras.getString("SMS_Body");
Log.e("????????????????SEND_SMS", "sms : "+sms);
sleep_time = extras.getString("Sleep_Time");
Log.e("????????????????Sleep_Time", "sleep_time : "+sleep_time);
Intent myIntent = new Intent(this, sendservicesms.class);
myIntent.putExtra("Phone_Number",phone_num);
myIntent.putExtra("SMS_Body",sms);
myIntent.putExtra("Sleep_Time",sleep_time);
startService(myIntent);
}
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sendsm, menu);
return true;
}
}
Service : sendservicesms.java
package com.qualcomm.sendsms;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;
public class sendservicesms extends IntentService {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used
public sendservicesms() {
super("sendservicesms");
}
public void onCreate() {
// The service is being created
}
#Override
protected void onHandleIntent(Intent intent) {
// The service is starting, due to a call to startService()
if(intent!=null) {
Bundle param = intent.getExtras();
if (param != null) {
String phone_no = (String)param.get("Phone_Number");
String sms_body = (String)param.get("SMS_Body");
String sleeptime = (String)param.get("Sleep_Time");
Log.e("????????????????SEND_SMS", "phno : "+phone_no);
Log.e("????????????????SEND_SMS", "sms : "+sms_body);
Log.e("????????????????Sleep_Time", "sleep_time : "+sleeptime);
Long time = Long.parseLong(sleeptime);
Log.e("????????????????time long", "Long_time : "+time);
try {
if(sleeptime!=null && sleeptime.length() > 0){
Thread.sleep(Long.parseLong(sleeptime));
}
Log.e("????????????????Sleep happened well", "sleep_time : "+sleeptime);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phone_no, null, sms_body, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
}
#Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
#Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
#Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}
LOGCAT:
E/AndroidRuntime(10276): FATAL EXCEPTION: main
E/AndroidRuntime(10276): java.lang.RuntimeException: Unable to start service com.qualcomm.sendsms.sendservicesms#418dd170 with Intent { cmp=com.qualcomm.sendsms/.sendservicesms (has extras) }: java.lang.NullPointerException
E/AndroidRuntime(10276): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2676)
E/AndroidRuntime(10276): at android.app.ActivityThread.access$1900(ActivityThread.java:144)
E/AndroidRuntime(10276): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1334)
E/AndroidRuntime(10276): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(10276): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(10276): at android.app.ActivityThread.main(ActivityThread.java:5074)
E/AndroidRuntime(10276): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(10276): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(10276): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(10276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(10276): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(10276): Caused by: java.lang.NullPointerException
E/AndroidRuntime(10276): at android.app.IntentService.onStart(IntentService.java:116)
E/AndroidRuntime(10276): at android.app.IntentService.onStartCommand(IntentService.java:130)
E/AndroidRuntime(10276): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2659)
You must call the super.onCreate() in the first line inside onCreate() if you override it, Cause system needs to be prepared before your own oncreate() implementation.....
Your program will be running fine if you do that
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Your rest of codes
}
When you remove onCreate() from your Activity, System will do that itself for you. :)
whenever there is a null pointer exception it is mostly due to xml... Some element may not be matching in your xml file.
to send sms u may try the following code:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", sms_text_string);
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

Categories