Good day. Please can someone help me with this?
Is it possible to upload images from android to remote database?
I'm able to communicate with my remote database and perform simple operations like read, write, and delete from database but I have a problem when it comes to uploading images. I'v spent my whole day searching trying and reading methods to accomplish this from stackoverflow and other websites.
This is what I have tried
public class MainActivity extends Activity {
Bitmap bitmap1;
byte[]image1byte;
...
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_1) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap1 = BitmapFactory.decodeFile(picturePath);
image1 = (ImageView) findViewById(R.id.imageView1);
image1.setImageBitmap(bitmap1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG,100,stream);
image1byte=stream.toByteArray();
}
and my AsyncTask task is;
class CreateNewMessage extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute(){
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setMessage("Uploading Message...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String topic=inputTopic.getText().toString();
String message=inputMessage.getText().toString();
String other=inputOther.getText().toString();
List<NameValuePair>params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("topic",topic));
params.add(new BasicNameValuePair("message",message));
params.add(new BasicNameValuePair("details",details));
params.add(new BasicNameValuePair("image",sendImage1));
JSONObject json=jsonParser.makeHttpRequest(url_create_message,"GET",params);
try {
response=json.getString(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response",json.toString());
return response;
}
protected void onPostExecute(String response) {
Toast.makeText(getBaseContext(),"Finished..Response= "+response,Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
but I get the following error;
12-12 16:22:47.017 15942-15985/com.example.mcleroy.studentboxadminpanel E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
Process: com.example.mcleroy.studentboxadminpanel, PID: 15942
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.mcleroy.studentboxadminpanel.MainActivity$CreateNewMessage.doInBackground(MainActivity.java:119)
at com.example.mcleroy.studentboxadminpanel.MainActivity$CreateNewMessage.doInBackground(MainActivity.java:96)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
12-12 16:22:48.286 15942-15942/com.example.mcleroy.studentboxadminpanel E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.mcleroy.studentboxadminpanel.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{4261d878 V.E..... R......D 0,0-684,192} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:376)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.example.mcleroy.studentboxadminpanel.MainActivity$CreateNewMessage.onPreExecute(MainActivity.java:104)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.mcleroy.studentboxadminpanel.MainActivity.createMessage(MainActivity.java:94)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3846)
at android.view.View.performClick(View.java:4466)
at android.view.View$PerformClick.run(View.java:18537)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5102)
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 de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Please please can anyone look into my code and tell me what I am not doing write, as I really need to be able to upload and download images from my app to remote database nd from remote database to app respectively. or is it impossible to accomplish this?
Here is my PHP script
<?php
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
$response = array();
$topic = $_GET['name'];
$message = $_GET['price'];
$details = $_GET['description'];
$image=$_GET['image'];
$con = mysql_connect($servername,$username,$password) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("INSERT INTO messages(topic, messages, others,image) VALUES('$name', '$price',`` '$description','$image')");
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Message successfully created.";
// echoing JSON response
echo json_encode($response);
}
?>
Thanks alot in advance as you try to help;
Related
I am developing an app in which my requirement to select an image from the SD card and send in to IBM Waston Visual Recognition service to identify the content in the image. I am doing like this..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == MainActivity.this.RESULT_OK && null != data){
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = MainActivity.this.getContentResolver().query(selectedImage,filePathColumn,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
analizarImagen(picturePath);
}
}
private void analizarImagen(String path){
File image = new File(path);
System.out.println(path);
VisualRecognition service = new VisualRecognition(VisualRecognition.VERSION_DATE_2016_05_20);
service.setApiKey("api-key");
ClassifyImagesOptions options = new ClassifyImagesOptions.Builder()
.images(image)
.build();
VisualClassification result = service.classify(options).execute();
System.out.println(result.toString());
}
But when I select an image, the application crashes
Error:
02-02 03:43:49.720 3355-3355/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/23 }} to activity {com.cucea.mauricio.visual/com.cucea.mauricio.visual.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3141)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184)
at android.app.ActivityThread.access$1100(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
at android.os.Handler.dispatchMessage(Handler.java:99)
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 java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at okhttp3.Dns$1.lookup(Dns.java:39)
at okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
at okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:172)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.execute(RealCall.java:57)
at com.ibm.watson.developer_cloud.service.WatsonService$1.execute(WatsonService.java:179)
at com.cucea.mauricio.visual.MainActivity.analizarImagen(MainActivity.java:84)
at com.cucea.mauricio.visual.MainActivity.onActivityResult(MainActivity.java:68)
at android.app.Activity.dispatchActivityResult(Activity.java:5192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3137)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184)
at android.app.ActivityThread.access$1100(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
You are hitting server from main(UI) thread which is not allowed in android. Call your analizarImagen() method in separate thread or async task.
Check this document:
https://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
im tryin to make an app and connect it to my database(MySQL wamp) . i have made my php files and this is the NewProductActivity.java file that's giving errors.I have made a sample to do so. I have got the code from here
package com.example.abc.androidhive;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NewProductActivity extends Activity {
// Progress Dialog
-private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://api.androidhive.info/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
the part giving errors is:
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
My Logcat is:
03-03 04:06:10.552 1944-1967/? E/JSON Parser: Error parsing data org.json.JSONException: Value Unknown of type java.lang.String cannot be converted to JSONObject
03-03 04:06:10.552 1944-1967/? W/dalvikvm: threadid=15: thread exiting with uncaught exception (group=0xb17d3678)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:841)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: Caused by: java.lang.NullPointerException
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at com.example.abc.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:100)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at com.example.abc.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:64)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-03 04:06:10.552 1944-1967/? E/AndroidRuntime: at java.lang.Thread.run(Thread.java:841)
Please suggest me of possible rectifications.
The problem is that what your server returns it's not a valid json. You should check what is the response of this call
I tried with casual params (name = a, price = b, description = c) and the server returns
Unknown database 'download_androidhive'
This is a string and 99% is the reason of your issue.
It's not because of this class, It is the error of your JSONParser class where these lines were written
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
I want to suggest you that it doesn't seems a single JsonObject at all. So just try replacing this line
jObj = new JSONObject(json);
with
JSONArray jsonArray = new JSONArray(json);
JSONObject jObj = jsonArray.getJSONObject(0);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
java.lang.NullPointerException occuring
Log-cat says Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
Here's my code:
I'm trying to get jSon data from a server(MySql) database, then displaying it in a list.
public class AllProducts extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> productsList;
private static String url_all_products = "http://server:host.../view.php";
private static final String TAG_SUCCESS="success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
JSONArray products=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
productsList=new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
Exception at new LoadAllProducts().execute();
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String,String,String>
Java.lang.NullPointerException Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
occuring at class LoadAllProducts extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog= new ProgressDialog(AllProducts.this);
pDialog.setMessage("Loading Products....Wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Exception at pDialog.show();
}
#Override
protected String doInBackground(String... params) {
ContentValues param=new ContentValues();
JSONObject json= jParser.makeHttpRequest(url_all_products,"GET",param);
Log.d("All Products: ", json.toString());
java.lang.NullPointerException occuring at Log.d("All Products: ", json.toString());
try{
int success=json.getInt(TAG_SUCCESS);
if(success==1)
{
products = json.getJSONArray(TAG_PRODUCTS);
for(int j=0; j<products.length() ; j++ )
{
JSONObject c = products.getJSONObject(j);
String id=c.getString(TAG_PID);
String name=c.getString(TAG_NAME);
HashMap<String,String> map=new HashMap<String,String>();
map.put(TAG_PID,id);
map.put(TAG_NAME,name);
productsList.add(map);
}
}
else {
Intent i=new Intent(getApplicationContext(),NewProduct.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
}
}
I have a button in my UI to get data from server and show it in a list, as i tap the button, pDialog shows and then the app goes "not responding" and these exceptions occur
Here is the LogCat
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:122)
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ ... 19 more
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
09-03 16:10:40.510 27696-31923/com.example.vashisht.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.vashisht.myapplication, PID: 27696
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.doInBackground(AllProducts.java:76)
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.doInBackground(AllProducts.java:57)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-03 16:10:40.980 27696-27696/com.example.vashisht.myapplication E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.vashisht.myapplication.AllProducts has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{10a4b377 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:382)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.onPreExecute(AllProducts.java:67)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.vashisht.myapplication.AllProducts.onCreate(AllProducts.java:50)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
09-03 16:10:44.250 27696-31923/com.example.vashisht.myapplication D/Process﹕ killProcess, pid=27696
09-03 16:10:44.260 27696-31923/com.example.vashisht.myapplication D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690
this means that the JSONObject json == null. You can check this in code before calling methods on the JSONObject. I guess you dont actually get data when you call the httprequest.
I make an android application on movies. I have a database movies. In the application I display the movies in ListView and I add a new movie.
I have a problem when I try to insert in my dataBase a new movie. Indeed, I have n error in my AsyncTask in the doInBackground but I don't know why. When I use the debugger, I have reject on the begin of the doInBackground at the line :
String title = eTitle.getText().toString();
So I give you my java code :
public class AddMovie extends Activity implements OnClickListener{
// Edit and Button that the user fill
private EditText eTitle, eActors, eDirector, eKind, eDate, eImage, eSummary ;
private Button bAdd;
// Progress Dialog
private ProgressDialog pDialog;
//JSON parser class
//JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
eTitle = (EditText)findViewById(R.id.title);
eActors = (EditText)findViewById(R.id.actors);
eDirector = (EditText)findViewById(R.id.director);
eKind = (EditText)findViewById(R.id.kind);
eDate = (EditText)findViewById(R.id.date);
eImage = (EditText)findViewById(R.id.image);
eSummary = (EditText)findViewById(R.id.summary);
bAdd = (Button)findViewById(R.id.addMovies);
bAdd.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.addMovies:
new AttempMovie().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case.
default:
break;
}
}
class AttempMovie extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddMovie.this);
pDialog.setMessage("Attempting for add new movie...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String title = eTitle.getText().toString();
String actors = eActors.getText().toString();
String director = eDirector.getText().toString();
String kind = eKind.getText().toString();
String date = eDate.getText().toString();
String image = eImage.getText().toString();
String summary = eSummary.getText().toString();
try {
// Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("title", title));
params.add(new BasicNameValuePair("actors", actors));
params.add(new BasicNameValuePair("director", director));
params.add(new BasicNameValuePair("kind", kind));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("image", image));
params.add(new BasicNameValuePair("summary", summary));
Log.d("request!", "starting");
JSONObject json = JSONfunctions.getJSONfromURL("http://10.0.0.35/BD_Enterprise_Mobility_Movies/add_movie.php");
// checking log for json response
Log.d("Register attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
Log.d("Successfully Register!", json.toString());
return json.getString(TAG_MESSAGE);
}
else
{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Intent i = new Intent(AddMovie.this,MainActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
startActivity(i);
Toast.makeText(AddMovie.this, message, Toast.LENGTH_LONG).show();
}
}
}
}
I give you also my JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject json = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
json = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return json;
}
}
And my error in the logcat:
03-20 18:28:19.753: E/AndroidRuntime(14656): FATAL EXCEPTION: AsyncTask #3
03-20 18:28:19.753: E/AndroidRuntime(14656): Process: com.mickKoza.jsonkoza, PID: 14656
03-20 18:28:19.753: E/AndroidRuntime(14656): java.lang.RuntimeException: An error occured while executing doInBackground()
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.lang.Thread.run(Thread.java:818)
03-20 18:28:19.753: E/AndroidRuntime(14656): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
03-20 18:28:19.753: E/AndroidRuntime(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.doInBackground(AddMovie.java:81)
03-20 18:28:19.753: E/AndroidRuntime(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.doInBackground(AddMovie.java:1)
03-20 18:28:19.753: E/AndroidRuntime(14656): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-20 18:28:19.753: E/AndroidRuntime(14656): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-20 18:28:19.753: E/AndroidRuntime(14656): ... 4 more
03-20 18:28:20.184: E/WindowManager(14656): android.view.WindowLeaked: Activity com.mickKoza.jsonkoza.AddMovie has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{3e1b7378 V.E..... R......D 0,0-1026,288} that was originally added here
03-20 18:28:20.184: E/WindowManager(14656): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-20 18:28:20.184: E/WindowManager(14656): at android.app.Dialog.show(Dialog.java:298)
03-20 18:28:20.184: E/WindowManager(14656): at com.mickKoza.jsonkoza.AddMovie$AttempMovie.onPreExecute(AddMovie.java:74)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.AsyncTask.execute(AsyncTask.java:535)
03-20 18:28:20.184: E/WindowManager(14656): at com.mickKoza.jsonkoza.AddMovie.onClick(AddMovie.java:54)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.View.performClick(View.java:4756)
03-20 18:28:20.184: E/WindowManager(14656): at android.view.View$PerformClick.run(View.java:19749)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Handler.handleCallback(Handler.java:739)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Handler.dispatchMessage(Handler.java:95)
03-20 18:28:20.184: E/WindowManager(14656): at android.os.Looper.loop(Looper.java:135)
03-20 18:28:20.184: E/WindowManager(14656): at android.app.ActivityThread.main(ActivityThread.java:5221)
03-20 18:28:20.184: E/WindowManager(14656): at java.lang.reflect.Method.invoke(Native Method)
03-20 18:28:20.184: E/WindowManager(14656): at java.lang.reflect.Method.invoke(Method.java:372)
03-20 18:28:20.184: E/WindowManager(14656): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
03-20 18:28:20.184: E/WindowManager(14656): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Thank you for your help
Michaël
One (or possibly all) of these views is null:
String title = eTitle.getText().toString();
String actors = eActors.getText().toString();
String director = eDirector.getText().toString();
String kind = eKind.getText().toString();
String date = eDate.getText().toString();
String image = eImage.getText().toString();
String summary = eSummary.getText().toString();
Possibly the view IDs that you're referencing during onCreate to find these views are not correct?
I am trying to use Voice Recognition on Android. Following is my code.
This is the code of the Button that is responsible to start speech recognition.
speak.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "City Name Please?");
startActivityForResult(intent, REQUEST_CODE);
}});
Here is a onActivityResult method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches_Text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.v("Results", matches_Text.get(0).toString());
//Update EditText cityname here
String normalized_cityname = matches_Text.get(0).toString().trim();
normalized_cityname = normalized_cityname.replace(" ","%20");
try {
getResponseString("http://api.openweathermap.org/data/2.5/weather?q="+normalized_cityname+"&units=metric", true);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The code worked ok but there are two problems I am encountering now and I am afraid that they may be related.
If I try to update text in an EditText instance cityname using cityname.setText(matches_Text.get(0).toString()), it crashes the app.
If I hit the speak button now, the google voice dialog comes up but shows can't reacg google at the moment.
Please suggest what can I do?
Adding the getResponseString method also.
public void getResponseString(String Url, boolean IsCalledOnVoiceInput) throws IOException, JSONException {
String temperature="";
String city;
String country;
String weather_main, weather_description;
MyAsyncTask xxx = new MyAsyncTask();
try {
String responseString = xxx.execute(Url).get();
TextView txtTemp = (TextView)findViewById(R.id.txt_temp);
TextView txtCity = (TextView)findViewById(R.id.txt_CityName);
TextView txtWeatherMain = (TextView)findViewById(R.id.textView2);
TextView txtWeatherDescription = (TextView)findViewById(R.id.textView3);
JSONObject reader = new JSONObject(responseString);
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
Log.v("temperarure",temperature);
city = reader.getString("name");
Log.v("city",city);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
Log.v("country",country);
JSONArray weather = reader.getJSONArray("weather");
JSONObject weather_obj = weather.getJSONObject(0);
weather_main = weather_obj.getString("main");
weather_description = weather_obj.getString("description");
txtTemp.setText(temperature+" °C");
txtCity.setText(city+" ("+country+")");
txtWeatherMain.setText(weather_main);
txtWeatherDescription.setText(weather_description);
if(IsCalledOnVoiceInput)
Speak_Weather_Data(city,temperature,weather_main,weather_description);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e){
e.printStackTrace();
}
}
Here is the log output
12-24 13:36:06.050 12164-12164/samarth.learning.http D/dalvikvm﹕ Late-enabling CheckJNI
12-24 13:36:06.300 12164-12164/samarth.learning.http D/Network﹕ Network
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Lat﹕ 28.8331443
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Long﹕ 78.7717138
12-24 13:36:06.360 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
12-24 13:36:06.370 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/04/13 Mon
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
12-24 13:36:06.430 12164-12164/samarth.learning.http D/OpenGLRenderer﹕ Enabling debug mode 0
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:08.232 12164-12164/samarth.learning.http W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
12-24 13:36:18.844 12164-12164/samarth.learning.http V/Results﹕ new delhi
12-24 13:36:18.844 12164-12164/samarth.learning.http D/AndroidRuntime﹕ Shutting down VM
12-24 13:36:18.844 12164-12164/samarth.learning.http W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4157c8b0)
12-24 13:36:18.854 12164-12164/samarth.learning.http E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { (has extras) }} to activity {samarth.learning.http/samarth.learning.http.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at samarth.learning.http.MainActivity.onActivityResult(MainActivity.java:160)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
12-24 13:36:22.558 12164-12164/samarth.learning.http I/Process﹕ Sending signal. PID: 12164 SIG: 9
is this what you mean?
i think matches_Text is sometimes NULL?! how about adding an
if(matches_Text == null){
Log.v("Results","matches_Text is NULL!");
return;
}
add above code just after ArrayList<String> matches_Text = da...