This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
Hi i want to fetch the selected column from mysql by matching one column name i.e
"select column_name from day where date='$date'"
But it is giving me serious error , i have check the connectivity issues they are fine , i think there is some problem in code please help me
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
public class Day extends Activity {
String dt="";
String mc="";
String bc="";
ImageView dateimg;
String name;
String date;
InputStream is=null;
String result=null;
String line=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.day_lay);
getCurrDate();
select();
dateimg = (ImageView) findViewById(R.id.img);
dateimg.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//getCurrDate();
}
});
}
public String getCurrDate()
{
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
mc = dt.substring(0, dt.length() - 17);
bc=mc.substring(4);
System.out.println("Date is"+bc);
date=bc;
return dt;
}
public void select()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("date",date));
try
{
HttpClient httpclient = new DefaultHttpClient()
HttpPost httppost = new HttpPost("http://192.168.1.1/wpcontent/themes/app/day.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
System.out.println("Got Value"+name);
}
}
// Database select
<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db="android";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$date=$_REQUEST['date'];
$r=mysql_query("select mat from vicks where date='$date'",$con);
while($row=mysql_fetch_array($r))
{
$flag[name]=$row[name];
}
print(json_encode($flag));
mysql_close($con);
?>
//Logcat
05-08 14:04:34.938: I/dalvikvm-heap(995): Grow heap (frag case) to 54.839MB for 2312016-byte allocation
05-08 14:04:35.218: D/dalvikvm(995): GC_CONCURRENT freed 1K, 4% free 56085K/58055K, paused 11ms+23ms
05-08 14:04:35.758: D/dalvikvm(995): GC_FOR_ALLOC freed 564K, 4% free 56086K/58055K, paused 172ms
05-08 14:04:35.788: I/dalvikvm-heap(995): Grow heap (frag case) to 57.044MB for 2312016-byte allocation
05-08 14:04:36.538: D/dalvikvm(995): GC_CONCURRENT freed <1K, 4% free 58344K/60359K, paused 11ms+98ms
05-08 14:08:30.258: I/System.out(995): Date is8
05-08 14:08:30.298: E/Fail 1(995): android.os.NetworkOnMainThreadException
05-08 14:08:30.338: E/Fail 2(995): java.lang.NullPointerException
05-08 14:08:30.338: E/Fail 3(995): java.lang.NullPointerException
05-08 14:08:30.338: I/System.out(995): Got valuenull
This is not about connectivity. This is about handling network activity on the main thread.
You can either disable that warning (which is bad practice) or perform that task in a separate thread.
A common Android pattern is using an AsyncTask for that.
The AsyncTask class uses three paramters in its constructor: params, progress, result. In your case they can all be null if you only need to run something in the background.
private class DatabaseTask extends AsyncTask<void, void, void>
{
protected void doInBackground(Void... params)
{
// YOUR DB CODE
}
}
And execute like this:
new DatabaseTask().execute();
Or, you can change the first void to whatever type you need if you want to use input parameters. Read more here.
Related
I am new to android and am trying to get a json file from an api and seem to be getting errors. I do not know where the error is coming from. I created a new thread and in the run method have the code to get the data from the api. I have the response string being logged but an error keeps coming up instead.
This is the code to my main activity
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.Buffer;
import java.util.*;
public class MainActivity extends AppCompatActivity implements BookListFragment.OnFragmentInteractionListener {
final ArrayList<Book> names = new ArrayList<Book>();
private boolean twoPane = false;
BookListFragment blf;
BookDetailsFragment bdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twoPane = findViewById(R.id.container2) == null;
Context context = getApplicationContext();
Resources res = context.getResources();
final String searchString = "";
Thread t = new Thread(){
#Override
public void run(){
URL bookData;
try{
bookData = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
HttpURLConnection conn = (HttpURLConnection) bookData.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String response = "", tmpResponse;
tmpResponse = br.readLine();
while(tmpResponse != null){
response= response + tmpResponse;
Log.d("response", tmpResponse);
tmpResponse = br.readLine();
}
Log.d("Response", response);
JSONObject bookObject = new JSONObject(response);
Message msg = Message.obtain();
msg.obj = bookObject;
} catch (Exception e){
e.printStackTrace();
}
}
};
/*if(twoPane){
ViewPagerFragment vp = ViewPagerFragment.newInstance(names);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container1,vp);
ft.commit();
} else {
blf = BookListFragment.newInstance(names);
bdf = BookDetailsFragment.newInstance(names.get(0));
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container1, blf);
ft.replace(R.id.container2,bdf);
ft.addToBackStack(null);
ft.commit();
}*/
}
Handler responseHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
JSONObject respObject = (JSONObject) msg.obj;
return false;
}
});
#Override
public void onItemSelection(Book bookname) {
bdf.updateBookName(bookname);
}
}
and this is the error
2019-11-14 16:47:38.682 2848-12759/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.b.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.microdetection.d.k.a(SourceFile:91)
at com.google.android.apps.gsa.staticplugins.microdetection.d.l.run(Unknown Source:14)
at com.google.android.libraries.gsa.runner.a.a.b(SourceFile:32)
at com.google.android.libraries.gsa.runner.a.c.call(Unknown Source:4)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at com.google.android.apps.gsa.shared.util.concurrent.b.g.run(Unknown Source:4)
at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
at com.google.android.apps.gsa.shared.util.concurrent.b.i.run(SourceFile:6)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.j(SourceFile:103)
at com.google.android.apps.gsa.speech.audio.au.read(SourceFile:2)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.ao.run(SourceFile:17)
at com.google.android.apps.gsa.speech.audio.an.run(SourceFile:2)
and this
2019-11-14 16:47:43.735 2848-12762/com.google.android.googlequicksearchbox:search W/ErrorProcessor: onFatalError, processing error from engine(4)
com.google.android.apps.gsa.shared.speech.b.g: Error reading from input stream
at com.google.android.apps.gsa.staticplugins.microdetection.d.k.a(SourceFile:91)
at com.google.android.apps.gsa.staticplugins.microdetection.d.l.run(Unknown Source:14)
at com.google.android.libraries.gsa.runner.a.a.b(SourceFile:32)
at com.google.android.libraries.gsa.runner.a.c.call(Unknown Source:4)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at com.google.android.apps.gsa.shared.util.concurrent.b.g.run(Unknown Source:4)
at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
at com.google.android.apps.gsa.shared.util.concurrent.b.aw.run(SourceFile:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
at com.google.android.apps.gsa.shared.util.concurrent.b.i.run(SourceFile:6)
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.
at com.google.android.apps.gsa.speech.audio.Tee.j(SourceFile:103)
at com.google.android.apps.gsa.speech.audio.au.read(SourceFile:2)
at java.io.InputStream.read(InputStream.java:101)
at com.google.android.apps.gsa.speech.audio.ao.run(SourceFile:17)
at com.google.android.apps.gsa.speech.audio.an.run(SourceFile:2)
The correct version of the code should the the data is got and saved into the response string and saves into a JSONObject. The correct output should be for the response string to be logged in the log cat.
good day sir. you open a connection but you did not connect to the url. try typing conn.connect()
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")
I am developing an app which includes the upload of all contacts to my server what i am doing is displaying all the contacts and sending them to my server as a string.Here is my code:
package com.example.core.freemusic;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MainActivity extends Activity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.LinearLayout1);
LoadContactsAyscn lca = new LoadContactsAyscn();
lca.execute();
}
class LoadContactsAyscn extends AsyncTask < Void, Void, String > {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Please Wait","");
}
#Override
protected String doInBackground(Void...params) {
String contacts = "";
Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts += contactName + ":" + phNumber + "\n";
}
c.close();
return contacts;
}
#Override
protected void onPostExecute(String contacts) {
super.onPostExecute(contacts);
pd.cancel();
TextView a = (TextView) findViewById(R.id.textView);
a.setText(contacts);
doInBackground(contacts);
}
protected void doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
try {
httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Actually the code shows no error but on running it in emulator it crashes.
the error on logcat is:
05-24 14:00:57.989 2488-2500/com.example.core.freemusic W/art﹕ Suspending all threads took: 5.841ms
05-24 14:00:57.992 2488-2500/com.example.core.freemusic I/art﹕ Background partial concurrent mark sweep GC freed 1888(115KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 502KB/1014KB, paused 6.923ms total 95.188ms
05-24 14:00:58.073 2488-2488/com.example.core.freemusic I/Choreographer﹕ Skipped 37 frames! The application may be doing too much work on its main thread.
05-24 14:00:58.080 2488-2488/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
05-24 14:00:58.102 2488-2488/com.example.core.freemusic D/AndroidRuntime﹕ Shutting down VM
05-24 14:00:58.103 2488-2488/com.example.core.freemusic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.core.freemusic, PID: 2488
java.lang.IllegalArgumentException: Illegal character in query at index 43: http://192.168.2.30/b.php?username=Sd:(546) 456-4826
Sad:486-44
at java.net.URI.create(URI.java:730)
at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:64)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-24 14:01:01.259 2488-2488/com.example.core.freemusic I/Process﹕ Sending signal. PID: 2488 SIG: 9
05-24 15:24:12.790 2685-2685/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
As error code state, you need to encode the query:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
need to changed into:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+java.net.URLEncoder.encode(params[0], "UTF-8"));
I have been stuck for weeks.....for this problem
I am using AsynTask to send data to php and recieve a name to print
but it showed this error anyone to help ??
12-29 19:34:12.623: D/dalvikvm(799): GC_CONCURRENT freed 188K, 11% free 2629K/2948K, paused 25ms+61ms, total 218ms
12-29 19:34:13.282: D/gralloc_goldfish(799): Emulator without GPU emulation detected.
12-29 19:34:42.132: W/System.err(799): java.lang.NullPointerException
12-29 19:34:42.164: W/System.err(799): at android.app.Activity.findViewById(Activity.java:1839)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.MainActivity.afterEffect(MainActivity.java:64)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.toPHP.onPreExecute(toPHP.java:47)
12-29 19:34:42.164: W/System.err(799): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
12-29 19:34:42.164: W/System.err(799): at android.os.AsyncTask.execute(AsyncTask.java:534)
12-29 19:34:42.164: W/System.err(799): at com.example.myweb.MainActivity$1.onClick(MainActivity.java:54)
12-29 19:34:42.172: W/System.err(799): at android.view.View.performClick(View.java:4204)
12-29 19:34:42.172: W/System.err(799): at android.view.View$PerformClick.run(View.java:17355)
12-29 19:34:42.172: W/System.err(799): at android.os.Handler.handleCallback(Handler.java:725)
12-29 19:34:42.185: W/System.err(799): at android.os.Handler.dispatchMessage(Handler.java:92)
12-29 19:34:42.185: W/System.err(799): at android.os.Looper.loop(Looper.java:137)
12-29 19:34:42.192: W/System.err(799): at android.app.ActivityThread.main(ActivityThread.java:5041)
12-29 19:34:42.212: W/System.err(799): at java.lang.reflect.Method.invokeNative(Native Method)
12-29 19:34:42.212: W/System.err(799): at java.lang.reflect.Method.invoke(Method.java:511)
12-29 19:34:42.212: W/System.err(799): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-29 19:34:42.222: W/System.err(799): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-29 19:34:42.222: W/System.err(799): at dalvik.system.NativeStart.main(Native Method)
JSONParser.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// 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;
}
}
toPHP.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class toPHP extends AsyncTask {
MainActivity main = new MainActivity();
private JSONParser jsonParser;
String email,password;
EditText emailBox;
EditText passwordBox;
#Override
protected void onPreExecute() {
super.onPreExecute();
main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
}
protected JSONObject doInBackground(String... args) {
toPHP userFunction = new toPHP();
JSONObject json = null;
try {
json = userFunction.getUserLoggedIn(email, password);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
public JSONObject getUserLoggedIn(String email,String password) throws ClientProtocolException, IOException, JSONException{
JSONObject json = null;
/*
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost/testand.php");
*/
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("email", email));
pairs.add(new BasicNameValuePair("password", password));
//post.setEntity(new UrlEncodedFormEntity(pairs));
//HttpResponse response = client.execute(post);
//HttpEntity resEntity = response.getEntity();
//if (resEntity != null) {
//String responseStr = EntityUtils.toString(resEntity).trim();
json = jsonParser.getJSONFromUrl("http://localhost/testand.php", pairs);
//}
return json;
}
protected void onPostExecute(JSONObject json) throws JSONException {
String myName = json.getString("name");
String str = myName + ", Welcome to Socionet. :) ";
main.afterEffect(str);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
return null;
}
}
MainActivity.java
package com.example.myweb;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
Button button;
EditText emailBox;
EditText passwordBox;
String emailId;
String passwordId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.login1);
emailBox = (EditText)findViewById(R.id.email);
passwordBox = (EditText)findViewById(R.id.password);
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void afterEffect(String str){
TextView textV1 = (TextView)findViewById(R.id.textV1);
textV1.setText(str);
}
}
UPDATE 1
new errors after #hasan83 's fixes
12-29 21:38:27.588: W/dalvikvm(1283): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
12-29 21:38:27.748: E/AndroidRuntime(1283): FATAL EXCEPTION: AsyncTask #1
12-29 21:38:27.748: E/AndroidRuntime(1283): java.lang.RuntimeException: An error occured while executing doInBackground()
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.lang.Thread.run(Thread.java:856)
12-29 21:38:27.748: E/AndroidRuntime(1283): Caused by: java.lang.NullPointerException
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.getUserLoggedIn(toPHP.java:99)
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.doInBackground(toPHP.java:67)
12-29 21:38:27.748: E/AndroidRuntime(1283): at com.example.myweb.toPHP.doInBackground(toPHP.java:1)
12-29 21:38:27.748: E/AndroidRuntime(1283): at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-29 21:38:27.748: E/AndroidRuntime(1283): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-29 21:38:27.748: E/AndroidRuntime(1283): ... 4 more
You can't create a new MainActivity in your AsyncTask. When you are in your MainActivity, pass the activity to the constructor of the AsyncTask. You will be able to get and update your views in the onPreExecute() method.
public class toPHP extends AsyncTask {
public toPHP(Activity activity) {
}
}
And in your activity:
new toPHP(MainActivity.this).execute();
Add a constructor so that you can pass in the current MainActivity to your AsyncTask
public class toPHP extends AsyncTask {
final MainActivity main;
public toPHP(MainActivity main) {
this.main = main;
}
...
then call like so
button.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
new toPHP(MainActivity.this).execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Error says it's unable to find your TextView with id of R.id.textV1. Make sure it's available in the content view :R.layout.activity_main
But the main problem is why are you doing this MainActivity main = new MainActivity(), in your AsyncTask. It should be passed by reference from the actual Activity.
Points:
I don't see #Override keyword before onPostExecute and doInBackground methods.
Move the code in onPreExecute to doInBackground.
Send the main activity as a parameter for the AsynkTask execute method.
Catch the activity on the do doInBackground.
dont' declare an object of toPhp just call getUserLoggedIn. you are in the same class.
That's it.
new toPHP().execute(MainActivity.this);
#Override
protected Object doInBackground(Object... args) {
main = (MainActivity) args[0];
main.afterEffect("sending...");
emailBox = (EditText) main.findViewById(R.id.email);
passwordBox = (EditText) main.findViewById(R.id.password);
email = emailBox.getText().toString();
password = passwordBox.getText().toString();
..
}
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