Getting force close when trying to parse JSON Object Android - java

I have created REST web service using jersey which returns JSON response. JSON response returned by web service is as follow-
{
"Disease": "Bacterial_blight",
"Control": "Foliar sprays of streptocycline sulphate # 0.5 gm/land copper-oxychlode # 3 g / l of water as and when symptoms seen."
}
I have made Android app activity for demo purpose which contains one radio button, one Edit text box and one Button to submit the parameters to REST web service. But Problem is I'm getting force close when I try to click on Submit Button.
This is the actual android activity class code-
package com.doitgeek.agroadvisorysystem;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class DiseaseResultActivity extends AppCompatActivity {
public TextView diseaseTV;
public TextView controlMechanismTV;
public EditText etSymptom;
public RadioButton rbL;
public Button btnSubmit;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disease_result);
diseaseTV = (TextView)findViewById(R.id.diseaseTV);
controlMechanismTV = (TextView)findViewById(R.id.controlMechanismTV);
etSymptom = (EditText)findViewById(R.id.etSymptom);
rbL = (RadioButton)findViewById(R.id.rbL1);
btnSubmit = (Button)findViewById(R.id.btnSubmit);
}
public void onClickSubmit(View view) {
RequestParams params = new RequestParams();
String affectedPart = rbL.getText().toString();
String symptom = etSymptom.getText().toString();
params.put("affectedPart", affectedPart);
params.put("symptom", symptom);
invokeWS(params);
}
/* Invocation of RESTful WS */
public void invokeWS(RequestParams params) {
dialog.show();
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.0.100:8080/AgroAdvisorySystem/webapi/disease_prediction/result", params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
dialog.hide();
try {
JSONObject obj = (JSONObject)new JSONTokener(response.toString()).nextValue();
JSONObject obj2 = obj.getJSONObject("Disease");
String disease = obj2.toString();
/*JSONObject obj = new JSONObject(response);
String disease = obj.getJSONObject("Disease").toString();*/
diseaseTV.setText(disease);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error Occurred [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
dialog.hide();
if(statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if(statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occurred! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}
}
I didn't find working solution till now that is why I am posting this as question.

So, what`s the Exception record?
It seems that the problem is in:
JSONObject obj2 = obj.getJSONObject("Disease");
where the item Disease is no longer a JSONObject.
Try obj.getSyting("Disease")

Related

How to navigate to specific activity/fragment after tapping on one signal push notification?

can someone provide me the proper documentation or code to navigate to specific activity by tapping on one signal push notification, i want to open the specific fragment
here is my code where i extened application class and initialize one signal :
package com.example.nasapp;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.util.Log;
import com.example.nasapp.ui.home.HomeFragment;
import com.example.nasapp.ui.information.InformationFragment;
import com.onesignal.OSMutableNotification;
import com.onesignal.OSNotification;
import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenedResult;
import com.onesignal.OSNotificationReceivedEvent;
import com.onesignal.OneSignal;
import org.json.JSONException;
import org.json.JSONObject;
public class OneSignalApplication extends Application {
private static final String ONESIGNAL_APP_ID = "e855e254-9b4e-4e6f-a64a-e48db6f35d07";
#Override
public void onCreate() {
super.onCreate();
// Enable verbose OneSignal logging to debug issues if needed.
//OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
// promptForPushNotifications will show the native Android notification permission prompt.
// We recommend removing the following code and instead using an In-App Message to prompt for notification permission (See step 7)
OneSignal.promptForPushNotifications();
OneSignal.setNotificationOpenedHandler(new OneSignal.OSNotificationOpenedHandler() {
#Override
public void notificationOpened(OSNotificationOpenedResult result) {
JSONObject data = result.getNotification().getAdditionalData();
Log.i("OneSignalExample", "Notification Data: " + data);
String notification_topic;
if (data != null) {
try {
System.out.println(data.getString("job_id"));
} catch (JSONException e) {
e.printStackTrace();
}
notification_topic = data.optString("notification_topic", "hii");
if (notification_topic != null) {
OneSignal.addTrigger("level", notification_topic);
}
}
}
});
}
}
here is my NotificationServiceExtensionClass:
public class NotificationServiceExtension extends Service implements OneSignal.OSRemoteNotificationReceivedHandler {
#Override
public void remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent) {
OSNotification notification = notificationReceivedEvent.getNotification();
// Example of modifying the notification's accent color
OSMutableNotification mutableNotification = notification.mutableCopy();
mutableNotification.setExtender(builder -> {
//... do stuff
builder.setTimeoutAfter(30000);
Intent intent = new Intent();
JSONObject data = notification.getAdditionalData();
// check the data and create intent
intent = new Intent(context, InformationFragment.class);
// or any other depends on data value
intent.putExtra("data", (Parcelable) data);
PendingIntent pendIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder = builder.setContentIntent(pendIntent);
return builder;
});
JSONObject data = notification.getAdditionalData();
Log.i("OneSignalExample", "Received Notification Data: " + data);
// If complete isn't call within a time period of 25 seconds, OneSignal internal logic will show the original notification
// To omit displaying a notification, pass `null` to complete()
notificationReceivedEvent.complete(mutableNotification);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
In manifest i declare this service class:
<service
android:name=".service.NotificationServiceExtension"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false">
am i missing some code or what am i doing wrong in code ,can please someone help?

Getting NullPointerException when inputting text in an EditText

An error occurs when searching for a city using the Android application. After I type a city, state, country (for example: New York, New York, US) and press the search button, the app crashes and gives me a NullPointerException.
MainActivity.java
package com.xxxx.weatherviewer;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// List of Weather objects representing the forecast
private List<Weather> weatherList = new ArrayList<>();
// ArrayAdapter for binding Weather objects to a ListView
private WeatherArrayAdapter weatherArrayAdapter;
private ListView weatherListView; // displays weather info
// configure Toolbar, ListView and FAB
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// autogenerated code to inflate layout and configure Toolbar
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// create ArrayAdapter to bind weatherList to the weatherListView
weatherListView = findViewById(R.id.weatherListView);
weatherArrayAdapter = new WeatherArrayAdapter(this, weatherList);
weatherListView.setAdapter(weatherArrayAdapter);
// configure FAB to hide keyboard and initiate web service request
FloatingActionButton fab =
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get text from locationEditText and create web service URL
EditText locationEditText =
findViewById(R.id.locationEditText);
URL url = createURL(locationEditText.getText().toString());
// hide keyboard and initiate a GetWeatherTask to download
// weather data from OpenWeatherMap.org in a separate thread
if (url != null) {
dismissKeyboard(locationEditText);
GetWeatherTask getLocalWeatherTask = new GetWeatherTask();
getLocalWeatherTask.execute(url);
}
else {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.invalid_url, Snackbar.LENGTH_LONG).show();
}
}
});
}
// programmatically dismiss keyboard when user touches FAB
private void dismissKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// create openweathermap.org web service URL using city
private URL createURL(String city) {
String apiKey = getString(R.string.api_key);
String baseUrl = getString(R.string.web_service_url);
try {
// create URL for specified city and imperial units (Fahrenheit)
String urlString = baseUrl + URLEncoder.encode(city, "UTF-8") +
"&units=imperial&cnt=16&APPID=" + apiKey;
return new URL(urlString);
}
catch (Exception e) {
e.printStackTrace();
}
return null; // URL was malformed
}
// makes the REST web service call to get weather data and
// saves the data to a local HTML file
private class GetWeatherTask extends AsyncTask<URL, Void, JSONObject> {
#Override
protected JSONObject doInBackground(URL... params) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) params[0].openConnection();
int response = connection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
StringBuilder builder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch (IOException e) {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.read_error, Snackbar.LENGTH_LONG).show();
e.printStackTrace();
}
return new JSONObject(builder.toString());
}
else {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.connect_error, Snackbar.LENGTH_LONG).show();
}
}
catch (Exception e) {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.connect_error, Snackbar.LENGTH_LONG).show();
e.printStackTrace();
}
finally {
assert connection != null;
connection.disconnect(); // close the HttpURLConnection
}
return null;
}
// process JSON response and update ListView
#Override
protected void onPostExecute(JSONObject weather) {
convertJSONtoArrayList(weather); // repopulate weatherList
weatherArrayAdapter.notifyDataSetChanged(); // rebind to ListView
weatherListView.smoothScrollToPosition(0); // scroll to top
}
}
// create Weather objects from JSONObject containing the forecast
private void convertJSONtoArrayList(JSONObject forecast) {
weatherList.clear(); // clear old weather data
try {
// get forecast's "list" JSONArray
JSONArray list = forecast.getJSONArray("list");
// convert each element of list to a Weather object
for (int i = 0; i < list.length(); ++i) {
JSONObject day = list.getJSONObject(i); // get one day's data
// get the day's temperatures ("temp") JSONObject
JSONObject temperatures = day.getJSONObject("temp");
// get day's "weather" JSONObject for the description and icon
JSONObject weather =
day.getJSONArray("weather").getJSONObject(0);
// add new Weather object to weatherList
weatherList.add(new Weather(
day.getLong("dt"), // date/time timestamp
temperatures.getDouble("min"), // minimum temperature
temperatures.getDouble("max"), // maximum temperature
day.getDouble("humidity"), // percent humidity
weather.getString("description"), // weather conditions
weather.getString("icon"))); // icon name
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the error message from the stacktrace:
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.xxxx.weatherviewer.MainActivity.convertJSONtoArrayList(MainActivity.java:171)
at com.xxxx.weatherviewer.MainActivity.access$300(MainActivity.java:30)
at com.xxxx.weatherviewer.MainActivity$GetWeatherTask.onPostExecute(MainActivity.java:157)
at com.xxxx.weatherviewer.MainActivity$GetWeatherTask.onPostExecute(MainActivity.java:106)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I believe there might be an issue with the line listed below:
JSONArray list = forecast.getJSONArray("list");
However, I am unsure of how to start....can someone please help me?
A simple fix could be to turn your catch block from:
catch (JSONException e) {
e.printStackTrace();
}
into:
catch (Exception e) {
e.printStackTrace();
}
This catches your NPE, but do note that, if you have an API for this the "list" value could be empty or having a null value in that case you can always have a checker before doing the operation on JSONArray list variable. So for example before doing this:
JSONObject day = list.getJSONObject(i);
you can surround it with:
if(forecast.has("list")) {
JSONObject day = list.getJSONObject(i);
// Same goes for day etc...
}
This ensures that it should check if the object exists in the first place before processing it to avoid NPE.

Why do I get the error unhandeled exception when trying to open my inputstream in Android studio? (code posted in description)

I am trying to read a file as inputstream to fill in the file with additional data. This data is then supposed to be sent over to a second activity which unwraps the data and displays it on the screen. this is my code
package com.example.daniel.finalproject;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class Secondactivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
}
public void Proceed(View view) {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
}
}
However this line: InputStream is = am.open("madlibsimple.txt");
returns the error. madlibsimple.txt is in the assetsfolder, but I
don't know what goes wrong. Any help would be much appreciated.
open(String file) can throw an error (i expect IOException) that you have to catch with an
try {
AssetManager am = getAssets();
InputStream is = am.open("madlibsimple.txt");
Story story = new Story(is);
EditText editText = (EditText)findViewById(R.id.word);
String text;
story.toString();
while (!story.isFilledIn()) {
story.read(is);
story.getNextPlaceholder();
text = editText.getText().toString();
story.fillInPlaceholder(text);
}
Intent intent = new Intent(this, Thirdactivity.class).putExtra("story",story);
startActivity(intent);
} catch (Exception e) {
e.printStacktrace();
}
statement.
This whole topic is not about what goes wrong, but what COULD go wrong
For more information on the topic of exceptions and errorhandling you can click here

App will not connect to Firebase Storage- Will not open, No errors

I was going through a tutorial to create a voice recorder which will then upload the recording to Firebase. I watched the tutorial many times and made sure the app is connected to Firebase; however, the app will not open right now most likely due to this issue. I'm pretty new to Java programming. Can someone please provide me with some guidance? Thank you
package bfb.ess.myapplicationbfb;
import android.app.ProgressDialog;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
public class speakp extends AppCompatActivity {
private Button mRecordBtn;
private TextView mRecordlabel;
private MediaRecorder mRecorder;
private String mFileName = null;
private static final String LOG_TAG = "Record_log";
private StorageReference mStorage;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordpage);
mStorage = FirebaseStorage.getInstance().getReference();
mRecordlabel = (TextView) findViewById(R.id.recordlabel);
mRecordBtn =(Button) findViewById(R.id.recordBtn);
mProgress = new ProgressDialog(this);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName +="/recorded_audio.3gp";
mRecordBtn.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
startRecording();
mRecordlabel.setText("Recording Started ...");
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
stopRecording();
mRecordlabel.setText("Recording Stopped ...");
}
return false;
}
});
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
uploadAudio();
}
private void uploadAudio() {
mProgress.setMessage("Uploading Audio ...");
mProgress.show();
StorageReference filepath = mStorage.child("Audio").child("new_audio.3gp");
Uri uri = Uri.fromFile(new File(mFileName));
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
mRecordlabel.setText("Uploading Finished");
}
});
}
}
Go to Firebase console and update read and write rules for storage
You can look into the Google Firebase Sample: Storage Sample
Please check the URI of audio file if its proper. Because I guess lastPathSegment of uri is getting faulty.
By Default:
service firebase.storage {
match /b/<name_of_app>/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Update it to:
service firebase.storage {
match /b/<name_of_app>/o {
match /{allPaths=**} {
allow read;
allow write;
}
}
}
NOTE:
This update will allow you to store the data even if you are not authorised.
It is only for development purpose because it can cause security issue of accessing the data without getting authorised.
So take care when uploading the app to play store, update this parameter and change according to your requirement.
You need to update the read and write rules for storage in your firebase console,
Go to Firebase console, select storage
Click on the Rules tab
By Default:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Change to:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
as Mohom.R said
NOTE: This update will allow you to store the data even if you are not authorised. It is only for development purpose because it can cause security issue of accessing the data without getting authorised. So take care when uploading the app to play store, update this parameter and change according to your requirement.

Android VMD MySQL insert and showing dialog

I am trying to do a simple insert from an Android application. I can run my php script from the browser by concatenating ?entry="Sample value from browser", but when I run the application from Android, I get no insert.
Here is where I am calling the insert class that uses JSON and implements AsyncTask:
package us.jtaylorok.android.sqlite.first;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class RemoteInsert extends AsyncTask<Void, String,String >{
protected String TAG;
protected Context context;
protected String input;
protected ProgressDialog progressDialog;
public RemoteInsert(String i,Context c){
this.input = i;
this.context = c;
}
protected void onPreExecute() {
//ProgressDialog progressDialog; // = new ProgressDialog(context);
//progressDialog=ProgressDialog.show(,"Please Wait..","Sending data to database", false);
progressDialog=ProgressDialog.show(context,"Please Wait..","Sending data to database", false);
}
#Override
protected String doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
//HttpPost httppost = new HttpPost("http://localhost/index.php");
//HttpPost httppost = new HttpPost("http://10.253.8.88/patient_data/patient_data.php");
HttpPost httppost = new HttpPost("http://10.100.205.72/patient_data/patient_data.php");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("entry", "Input from Android"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
} catch(Exception e) {
Log.e(TAG, "Error: "+e.toString());
}
return "";
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
Toast.makeText(context, "Finished", Toast.LENGTH_LONG).show();
}
}
And here is my PHP script:
<?php
// mysql_connect("host","username","password");
mysql_connect("localhost","user1","mypassword");
mysql_select_db("test");
$entry_value = $_REQUEST["entry"];
$query = "INSERT INTO patientdata (entry) values (".$entry_value.");";
if( !mysql_query($query) ) {
/*insert failed*/
}
mysql_close();
?>
Again, this works perfectly if I call it from the browser, but it throws an exception before implementing AsyncTask.
I do get the AVD to display the add and remove, but when I do that there is no request in my apache2 access_log or error_log. Any suggestions?
I think you have stored php script on local server. So use this 10.0.2.2 while initializing HttpPost instead of your machine's ip address. Its localhost equivalent in android Virtual device.
That was not the issue for this particular problem. The issue was a magic quotes setting in the php.ini

Categories

Resources