java.lang.NullPointerException occuring, developing android, how do I fix that? [duplicate] - java

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.

Related

Android IAP getPurchases NullPointerException

I have implemented the In-App Billing feature in my app, it works on most of the devices but some of them reported a null pointer exception. Here are the stacktrace:
Fatal Exception: java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
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 'long java.lang.Long.longValue()' on a null object reference
at android.os.Parcel.readException(Parcel.java:1552)
at android.os.Parcel.readException(Parcel.java:1499)
at com.android.vending.billing.IInAppBillingService$Stub$Proxy.getPurchases(IInAppBillingService.java:349)
at com.vectorspace.roadcon.MyApplication$1$1.doInBackground(MyApplication.java:84)
at com.vectorspace.roadcon.MyApplication$1$1.doInBackground(MyApplication.java:78)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
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)
And I am running the above code inside an Asynctask in OnServiceConnected:
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
AsyncTask<Object, Void, Bundle> getPurchasedItemTask = new AsyncTask<Object, Void, Bundle>() {
#Override
protected Bundle doInBackground(Object... objects) {
try {
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
return ownedItems;
} catch (RemoteException e) {
e.printStackTrace();
}
return null;
}
I have no idea what's wrong, please help.

Fatal exception at main android during dropbox authentication [duplicate]

This question already exists:
Dropbox Core API is not working. I don't want to hardcode app key and secret?
Closed 7 years ago.
I am getting fatal exception error at main nullpointer exception. basically i have 2 activities login and main activity.you will enter app key and app secret in login activity then after authentication it will take you to main activity any help ??
login activity
public class login_activity extends AppCompatActivity {
public String APP_kEY ;
public String APP_SECRET;
public String accessToken;
EditText app_key_view;
EditText App_secret_view;
Button dropbox;
public DropboxAPI<AndroidAuthSession> mDBApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences pref = getSharedPreferences("login",MODE_PRIVATE);
APP_kEY = pref.getString("appkey",null);
APP_SECRET = pref.getString("appsecret",null);
accessToken = pref.getString("access",null);
if (accessToken != null){
AppKeyPair appkeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appkeys);
session.setOAuth2AccessToken(accessToken);
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity);
app_key_view=(EditText)findViewById(R.id.app_key_text);
App_secret_view=(EditText)findViewById(R.id.app_secret_text);
dropbox = (Button)findViewById(R.id.link_dropbox);
//////////////////////////////////////////////////////////////
dropbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
APP_kEY = app_key_view.getText().toString();
APP_SECRET = App_secret_view.getText().toString();
AppKeyPair appKeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<>(session);
mDBApi.getSession().startOAuth2Authentication(login_activity.this);
}
});
}
#Override
protected void onResume () {
super.onResume();
if(mDBApi.getSession().authenticationSuccessful()){
try {
mDBApi.getSession().finishAuthentication();
accessToken = mDBApi.getSession().getOAuth2AccessToken();
SharedPreferences.Editor editor = getSharedPreferences("login",MODE_PRIVATE).edit();
editor.putString("appkey",APP_kEY);
editor.putString("appsecret",APP_SECRET);
editor.putString("access",accessToken);
editor.commit();
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
catch (IllegalStateException e){
Log.i("DbAuthLog", "Error authenticationg", e);
}
}
}
Logcat
09-11 21:06:01.947 3842-3842/? I/art﹕ Late-enabling -Xcheck:jni
09-11 21:06:01.975 3842-3851/? I/art﹕ Debugger is no longer active
09-11 21:06:02.370 3842-3857/? I/art﹕ Background sticky concurrent mark sweep GC freed 2909(253KB) AllocSpace objects, 2(32KB) LOS objects, 0% free, 50MB/50MB, paused 36.891ms total 133.660ms
09-11 21:06:02.803 3842-3842/? D/AndroidRuntime﹕ Shutting down VM
09-11 21:06:02.803 3842-3842/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ayzaz.timescopev1.timescope, PID: 3842
java.lang.RuntimeException: Unable to resume activity {com.example.ayzaz.timescopev1.timescope/com.example.ayzaz.timescopev1.timescope.login_activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2986)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at com.example.ayzaz.timescopev1.timescope.login_activity.onResume(login_activity.java:77)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2975)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-11 21:06:05.849 3842-3842/com.example.ayzaz.timescopev1.timescope I/Process﹕ Sending signal. PID: 3842 SIG: 9
onResume() always gets called after onCreate().
When onResume() begins, mDBApi is null, because this field is only ever assigned in the onClick() method.
You either need to assign mDBApi in onCreate() directly, or you need to check that it is not null before you try to use it.

Get List<string> from db class and store in other class

I am creating a selection of questions in my db class (SQLDatabaseHelper.java) and have a method which creates a ListArray for use in other classes:
public List<List<String>> getAllAnswersByQuestion2() {
List<String> array1 = new ArrayList<String>();
List<String> array2 = new ArrayList<String>();
//Clear arrays just in case they still existed and had values
array1.clear();
array2.clear();
SQLiteDatabase db = this.getReadableDatabase();
//Get 5 random values from the questions table
String selectQuery = "SELECT DISTINCT questionDescr, answerSetId FROM " + TABLE_QUESTION + " ORDER BY RANDOM() LIMIT 5";
Cursor c = db.rawQuery(selectQuery, null);
try {
//Ignore any null values in the table, go the first value
if (c!= null && c.moveToFirst())
{
do {
//Create two strings - one for all question descriptions and one for answersetIDs
String questdescr = c.getString(c.getColumnIndex(QDESCR));
String answerSetIds = c.getString(c.getColumnIndex(ASID));
//Put these strings into two separate arrays
array1.add(questdescr);
array2.add(answerSetIds);
//And when all values have been put into arrays......
} while (c.moveToNext());
}
//Create another array to bundle up the two arrays already created
List< List<String> > listArray = new ArrayList< List<String> >();
//Clear this array just in case of residual values
listArray.clear();
listArray.add(array1);
listArray.add(array2);
//Return this array to be picked up in the 'showRandomNextQuestion' method
return listArray;
} finally {
//Close cursor and database to prevent memory leaks
c.close();
db.close();
}
}
I have a separate class (QuizQuestionBank.java) which tries to take the returned ListArray and splits it into two separate List for further use:
import java.util.List;
import android.app.Application;
public class QuizQuestionBank extends Application {
Object db;
#SuppressWarnings("unused")
private List<String> questionStrings;
public List<String> getQuestionStrings() {
SQLDatabaseHelper db = new SQLDatabaseHelper(QuizQuestionBank.this);
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion2();
//Get the question/text/answer Strings
List<String> questionStrings = listList.get(0); //question Strings
return questionStrings;
}
public List<String> setQuestionStrings(List<String> questionStrings) {
return this.questionStrings = questionStrings;
}
}
And finally I have a MainActivity that tries to get the List from my QuizQuestionBank class, and use that to get a value within to then output into a textview:
private class showNextRandomQuestion1 extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
QuizQuestionBank qb = new QuizQuestionBank();
//question Strings
List<String> questionStrings = qb.getQuestionStrings();
//Generate random index
Random r = new Random();
int rand = Math.abs((r.nextInt() % questionStrings.size()));
String questionString = questionStrings.get(rand);
//remove and square brackets from array of strings
String regex = "\\[|\\]";
aQuestionString = questionString.replaceAll(regex, "");
return aQuestionString;
}
#Override
protected void onPostExecute(String result) {
//take returned question from above and display it
questionView.setText(aQuestionString);
}
}
however, I am currently getting the following errors when my 'showNextRandomQuestion1()' method is called:
08-31 19:24:55.637: I/Choreographer(20638): Skipped 63 frames! The application may be doing too much work on its main thread.
08-31 19:24:55.887: I/ActivityManager(20638): Timeline: Activity_idle id: android.os.BinderProxy#41ec2f08 time:939408562
08-31 19:25:01.887: W/dalvikvm(20638): threadid=13: thread exiting with uncaught exception (group=0x41a71d88)
08-31 19:25:02.037: E/AndroidRuntime(20638): FATAL EXCEPTION: AsyncTask #2
08-31 19:25:02.037: E/AndroidRuntime(20638): Process: com.example.quizapp, PID: 20638
08-31 19:25:02.037: E/AndroidRuntime(20638): java.lang.RuntimeException: An error occured while executing doInBackground()
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.os.AsyncTask$3.done(AsyncTask.java:300)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.lang.Thread.run(Thread.java:841)
08-31 19:25:02.037: E/AndroidRuntime(20638): Caused by: java.lang.NullPointerException
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:263)
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
08-31 19:25:02.037: E/AndroidRuntime(20638): at com.example.quizapp.SQLDatabaseHelper.getAllAnswersByQuestion2(SQLDatabaseHelper.java:445)
08-31 19:25:02.037: E/AndroidRuntime(20638): at com.example.quizapp.QuizQuestionBank.getQuestionStrings(QuizQuestionBank.java:20)
08-31 19:25:02.037: E/AndroidRuntime(20638): at com.example.quizapp.MainActivity$showNextRandomQuestion1.doInBackground(MainActivity.java:371)
08-31 19:25:02.037: E/AndroidRuntime(20638): at com.example.quizapp.MainActivity$showNextRandomQuestion1.doInBackground(MainActivity.java:1)
08-31 19:25:02.037: E/AndroidRuntime(20638): at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-31 19:25:02.037: E/AndroidRuntime(20638): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-31 19:25:02.037: E/AndroidRuntime(20638): ... 4 more
08-31 19:25:02.227: W/dalvikvm(20638): threadid=14: thread exiting with uncaught exception (group=0x41a71d88)
08-31 19:25:02.227: I/Process(20638): Sending signal. PID: 20638 SIG: 9
It seems it is having initial trouble when my QuizQuestionBank class is trying to retrieve the listarray from the db helper class. Anyone see what I need to do to get around this? Many thanks
Try this in your onPostExecute:
Change this
questionView.setText(aQuestionString);
to
questionView.setText(result);

Insert into database AsyncTask error

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?

Uploading images to remote MySQL server

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;

Categories

Resources