Android, it failed to upload an image to server - java

I am trying to upload an image file using multipart method to the server.
Here are my codes.
package com.example.test_multipart;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener() {
TestAsyncTask asyncTask = new TestAsyncTask();
#Override
public void onClick(android.view.View v) {
// TODO Auto-generated method stub
new TestAsyncTask().execute();
}
});
}
public class TestAsyncTask extends AsyncTask<HttpResponse, Integer, Long> {
private ProgressDialog mDialog = new ProgressDialog(MainActivity.this);
long totalSize;
String url = "http://bridgecall.co.kr:5000/apis/settings/profile_update";
#Override
protected Long doInBackground(HttpResponse... arg0) {
// Register parameters
Map<String, Object> params = new HashMap<String, Object>();
params.put("phone", "01030195208");
params.put("name", "YUJIHYN");
Map<String, File> fileParams = new HashMap<String, File>();
File f = new File("/DCIM/Camera/test.jpg");
fileParams.put("file", f);
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Accept-Charset", "UTF-8");
httpPost.setHeader("ENCTYPE", "multipart/form-data");
CustomMultipartEntity multipart = new CustomMultipartEntity(
new ProgressListener() {
#Override
public void transferred(long transferred) {
// TODO Auto-generated method stub
publishProgress((int) transferred);
}
});
// Params
for (String strKey : params.keySet()) {
StringBody body = new StringBody(params.get(strKey)
.toString());
multipart.addPart(strKey, body);
}
// attach a file
for (String keys : fileParams.keySet()) {
multipart.addPart(keys, new FileBody(fileParams.get(keys)));
}
totalSize = multipart.getContentLength();
mDialog.setMax((int) totalSize);
httpPost.setEntity(multipart);
HttpResponse response = httpClient.execute(httpPost);
Log.v("checkcheckcheckcheck ", "checkcheckcheckcheck");
HttpEntity entity=response.getEntity();
InputStream is = entity.getContent();
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).append("\n");
}
is.close();
} catch (Exception e) {
return 0L;
}
return 0L;
}
#Override
protected void onCancelled() {
super.onCancelled();
mDialog.dismiss();
}
#Override
protected void onPostExecute(Long result) { // ui.
super.onPostExecute(result);
mDialog.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mDialog.setCancelable(true);
mDialog.setOnCancelListener(cancelListener);
mDialog.setMessage("Uploading...");
mDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// Progress update
mDialog.setProgress((int) progress[0]);
}
OnCancelListener cancelListener = new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
}
};
}
}
It doesn't work after this line.
Log.v("checkcheckcheckcheck ", "checkcheckcheckcheck");
I get 400 error from the server.
It works fine if I upload an image on HTML. Can you see what is the problem?

Related

Java Interface Callback on Android

I am currently trying to make an android app that basically downloads strings from a url. But I want to make it object oriented. My mainActivity gets string from webService which downloads string when button is clicked. But I am not good at interfaces and callbacks. What should I do to make this code run?
public class MainActivity extends Activity implements WebServiceInterface{
private TextView textView;
private Button readWebPage;
private WebService service;
private WebServiceInterface webServiceInterface;
private String response;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
readWebPage = (Button) findViewById(R.id.readWebpage);
service = new WebService();
readWebPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
service.execute(new String[]{"http://google.com/"});
onSuccess(response);
}
});
}
#Override
public void onSuccess(String response) {
textView.setText(Html.fromHtml(response));
}
#Override
public void onFail(Exception ex) {
textView.setText(ex.getLocalizedMessage());
}
}
public class WebService extends AsyncTask<String, Void, String> {
private WebServiceInterface webServiceInterface;
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
webServiceInterface.onSuccess(response);
} catch (Exception e) {
e.printStackTrace();
webServiceInterface.onFail(e);
}
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
public interface WebServiceInterface {
void onSuccess(String response);
void onFail(Exception ex);
}
you need to create one public method for set webServiceInterface in WebService class like
public setWebServiceInterface (WebServiceInterface listener)
{
this.webServiceInterface =listener;
}
in MainActivity activity call this method and pass argument this
service.setWebServiceInterface (this);
in WebService class in onPostExecute Method call
webServiceInterface.onSuccess(s);
Add WebService (WebServiceInterface webServiceInterface) in your AsyncTask as a constructor.
service = new WebService(new WebServiceInterface (){
void onSuccess(String response){
//do your stuff
}
void onFail(Exception ex){
//do your stuff
}
});
and in your asynctask
public class WebService extends AsyncTask<String, Void, String> {
public WebService (WebServiceInterface webServiceInterface){
this.webinterface= webServiceInterface;
}
private WebServiceInterface webinterface;
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
webinterface.onSuccess(response);
} catch (Exception e) {
e.printStackTrace();
webinterface.onFail(e);
}
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
I have found the problem, it is because of runOnUiThread is missing.

Get variable value OnpostExecute (Async)

I need to get the value of an id that is within my OnpostExecute.
Look into my class that contains OnPostExecute:
listaPedido.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> lista, View item, int posicao, long id) {
listaPedido.getItemAtPosition(posicao);
if (posicao == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(FinalizarPedido.this);//Cria o gerador do AlertDialog
builder.setTitle("Item: " + posicao);
builder.setMessage("Categoria: " + pedidos_categoria.get(0) + "\nDescrição: " + pedidos_descricao.get(0) + "\nQtd: " + pedidos_qtd.get(0) + "\nUnidade: " + pedidos_unidade.get(0));
builder.setNegativeButton("Fechar", null);
builder.setPositiveButton("Excluir", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String id = pedidos_id.get(0);
new delete().execute();
}
});
alerta = builder.create();
alerta.show();
So I try to change my class to delete calling the String value "id", but I can not in any way take this value OnPostExecute.
class delete extends android.os.AsyncTask<String, Integer, String> {
private StringBuilder sb;
private ProgressDialog pr;
private HttpResponse req;
private InputStream is;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FinalizarPedido.this);
pDialog.setMessage("Excluindo pedido ...");
pDialog.setIndeterminate(false); pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
UserAccessSession userAccess = UserAccessSession.getInstance(FinalizarPedido.this);
UserSession userSession = userAccess.getUserSession();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
select objetoselect = new select();
nameValuePairs.add(new BasicNameValuePair("pedidos_id", objetoselect.id));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://guiaserudgeramos.com.br/buysell/pedidos_del.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
InputStreamReader ireader = new InputStreamReader(is);
BufferedReader bf = new BufferedReader(ireader);
sb = new StringBuilder();
String line = null;
while ((line = bf.readLine()) != null) {
sb.append(line);
}
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();
}
return id;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "Pedido deletado com sucesso", Toast.LENGTH_LONG).show();
}
}
}
I didn't understand what you was doing but you can do it with using this way. You have to get some variables and classes from another Activity by delete class Constructor.
class delete extends android.os.AsyncTask<String, Integer, String> {
private StringBuilder sb;
private ProgressDialog pr;
private HttpResponse req;
private InputStream is;
private Context context;
public delete(Context _context, ProgressDialog dialog, InputStream input )
{
context = _context;
pr = dialog;
is = input;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
/*
Your operations
*/
}
#Override
protected String doInBackground(String... arg0) {
/*
Your operations
*/
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
/*
Your operations
*/
}
}
}

Get a variable form onItemListener and use it in another function

private class BackTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
// i want to use httppost in this ligne
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); // close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 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("ERROR", "Error converting result " + e.toString());
}
// parse json data
try {
result = result.substring(result.indexOf("["));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Prog2 p = new Prog2();
p.setTitre_emission(json_data.getString("titre_emission"));
p.setDesc_emission(json_data.getString("desc_emission"));
p.setHeure_emission(json_data.getString("heure_emission"));
p.setChaine_emission(json_data.getString("titre_chaine"));
records.add(p);
}
}
catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null)
pd.dismiss(); // close dialog
Log.e("size", records.size() + "");
adapter.notifyDataSetChanged(); // notify the ListView to get new
// records
}
}
How can I get a text from onItemListener and use it in an other function for getting an httpost?
When I use getText() I get an error
public class Wataneya1Activity extends AppCompatActivity {
Toolbar mToolbar;
Spinner mSpinner;
String text;
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter1 adapter;
ListView listProg;
ArrayList<Prog1> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wataneya1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageButton mButton = (ImageButton) findViewById(R.id.Button03);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wataneya1Activity.this.finish();
}
});
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
final ActionBar actionBar = getSupportActionBar();
mSpinner = (Spinner) findViewById(R.id.spinner_rss);
String[] items = getResources().getStringArray(R.array.days_array);
List<String> spinnerItems = new ArrayList<>();
for (int i = 0; i < items.length; i++) {
spinnerItems.add(items[i]);
}
SpinnerAdapter adapter1 = new SpinnerAdapter(actionBar.getThemedContext(), spinnerItems);
mSpinner.setAdapter(adapter1);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2, long arg3) {
text = mSpinner.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
context = this;
records = new ArrayList<Prog1>();
listProg = (ListView) findViewById(R.id.prog_list);
adapter = new CustomAdapter1(context, R.layout.list_item, R.id.titre_emission, records);
listProg.setAdapter(adapter);
}
public HttpPost fnt (String text) {
if (text.equals("Mardi")) {
httppost = new HttpPost("http://192.168.:8080/TuniTV/prog_wataneya1_mardi.php");
} else if (text.equals("Mercredi")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_mercredi.php");
} else if (text.equals("Jeudi")) {
httppost = new HttpPost("http://192.168/TuniTV/prog_wataneya1_jeudi.php");
} else if (text.equals("Vendredi")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_vendredi.php");
} else if (text.equals("Samedi")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_samedi.php");
} else if (text.equals("Dimanche")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_dimanche.php");
} else {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_lundi.php");
}
return httppost;
}
You receive the click position ( == index into your data) in the callback method. Use it to find the data in your data array.
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2, long arg3) {
text = spinnerItems.get(arg3);
Toast.makeText(getApplicationContext(), text,
Toast.LENGTH_SHORT).show();
}
Btw... Telling us there is a mistake - is crap.
Telling us what kind of mistake it is or even showing some stacktrace? Great stuff.

How to integrate with jsonwebservices in Android?

I'm implementing json_web services in my Android application. I want to send the json data on jsonwebservices which is created in Java. When I run the application data does not send from the Android and does not show any error and also does not show any type of exception.
How can I identify whether my data is sent or not?
Here is my Activity Code:
public class Login extends Activity
{
Button btnLogin;
EditText etextUsername , etextPassword;
String strUserName , strPassWord ;
ProgressDialog pDialog;
JSONObject jObject ;
SharedPreferences.Editor editor;
SharedPreferences sharedPref1;
String str_Device_IP_Address=null;
JSONArray user = null;
String pref_filename = "IP_ADDRESS";
static final String KEY_REQUEST_ID = "RequestId";
static final String KEY_REQUEST_CODE = "RequestCode";
static final String KEY_CHANNEL_ID = "ChannelId";
static final String KEY_IP_ADDRESS="IPAddress";
static final String KEY_USERNAME="UserId";
static final String KEY_PASSWORD="Password";
static final String KEY_REQUEST="Request";
static final String KEY_VENDOR_ID="VendorId";
String RequestId="77777";
String RequestCode="001";
String stringChannelId="MobileApp";
String strIpAddress = null;
private String textToEncrypt = "Hi, this is a test to check its gone work or not.";
String encrypted = "MzA3RDBCMjMxMjQzNzcxREUxMUYxNjg1NzgwOTU1MjU1M0FDOUZEN0M3Q0JGQ0Q5MTI2NEIyNTE2"
+ "OTQwQTc3NjM2QTBCRDFDMUEyNkUwRjlDMzQwN0U0MEI0NDg2M0JBMDU1OThCNTI1NTZCMEFGNjk1NjJFNzZBMUE0NzM4NTQ=";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final Context context = getApplicationContext();
connectWithHttpGet_IpAddress();
etextUsername = (EditText)findViewById(R.id.edittext_username);
etextPassword = (EditText)findViewById(R.id.edittext_password);
btnLogin=(Button)findViewById(R.id.button_Login);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if (!isOnline())
{
showNoConnectionDialog(Login.this);
}
else
{
connectWithHttpGet_LoginData();
}
}
});
}
private void connectWithHttpGet_LoginData()
{
class GetJSONParse extends AsyncTask<String, Integer, JSONObject>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
str_Device_IP_Address=sharedPref1.getString("ip_address", "a\n");
System.out.println("strCode in Gsk_Demo ="+str_Device_IP_Address);
strUserName = etextUsername.getText().toString().trim();
strPassWord = etextPassword.getText().toString().trim();
pDialog = new ProgressDialog(Login.this);
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
System.out.println("Progress Dialog!!!!!!!!!!!!!!!!!!!!!!!");
}
#Override
protected JSONObject doInBackground(String... args)
{
String strUrl = "http://test.xxxxxx.com/cms/json/w2iWS";
JSONParser jParser = new JSONParser();
Log.e("DoinBackground !!!!!","Method");
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(strUrl);
String jsonString=json.toString();
Log.e("jsonString in DoinBackground !!!!!","Method" + jsonString);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
try
{
// Getting JSON Array
user = json.getJSONArray( KEY_REQUEST_ID );
JSONObject jsonObject = user.getJSONObject(0);
jsonObject.put(KEY_REQUEST_CODE, RequestCode);
jsonObject.put(KEY_CHANNEL_ID, stringChannelId);
jsonObject.put(KEY_IP_ADDRESS, str_Device_IP_Address);
jsonObject.put(KEY_USERNAME, strUserName);
jsonObject.put(KEY_PASSWORD, strPassWord);
String encrypted1 = EncodeDecodeAES.encrypt(jsonObject.toString(), textToEncrypt);
System.out.println("encrypted1 =" + encrypted1);
JSONObject inner = new JSONObject();
inner.put(KEY_REQUEST, encrypted1);
inner.put(KEY_VENDOR_ID, "1");
String decrypted = EncodeDecodeAES.decrypt(jsonObject.toString(), encrypted);
System.out.println("decrypted =" + decrypted);
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GetJSONParse getjsonparse = new GetJSONParse();
getjsonparse.execute();
}
// Get Ip Address
private void connectWithHttpGet_IpAddress() {
class httpGetAsynchTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
String url = "http://api.externalip.net/ip";
Log.e("!!STRING URL DATE DETAIL", "" + url);
HttpGet httpGet = new HttpGet(url);
Log.e("", "" + httpGet);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.e("HTTP.RESPONSE.DATE.DTAIL", "" + httpResponse);
System.out.println("HTTPRESPONSE");
InputStream inpustream = httpResponse.getEntity()
.getContent();
InputStreamReader inputstreamreader = new InputStreamReader(
inpustream);
BufferedReader bufferedreader = new BufferedReader(
inputstreamreader);
StringBuilder stringbuilder = new StringBuilder();
Log.e("", "" + stringbuilder);
String strbuffer = null;
while ((strbuffer = bufferedreader.readLine()) != null)
{
stringbuilder.append(strbuffer);
}
String strResponse = stringbuilder.toString();
/****************** Code For Shared Preferences **************************************/
sharedPref1 = getSharedPreferences(pref_filename, 0);
editor = sharedPref1.edit();
editor.putString("ip_address", strResponse);
Log.e("Returning value of doInBackground REsponse:" ,strResponse);
System.out.println("IPADDRESS IN DOIN BACKGRAOUND");
editor.commit();
/***************** Code For Shared Preferences **************************************/
}
catch (ClientProtocolException cpe) {
cpe.printStackTrace();
Log.e("Exception generates caz of httpResponse :", "-"
+ cpe);
}
catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Second exception generates caz of httpResponse :",
"-" + ioe);
}
return null;
}
}
httpGetAsynchTask httpGetAsyncTask = new httpGetAsynchTask();
httpGetAsyncTask.execute();
}
public static void showNoConnectionDialog(final Login login)
{
AlertDialog.Builder builder = new AlertDialog.Builder(login);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
login.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
}
Asynctask is not invoked
JSONParse jp =new JSONParse();
jp.execute(params);
http://developer.android.com/reference/android/os/AsyncTask.html
public final AsyncTask<Params, Progress, Result> execute (Params... params)
Executes the task with the specified parameters.
You had no invoked asynctask before
GetJSONParse get = new GetJSONParse();
get.execute(params);
And you said i can't see the log message in doInbackground. i just ran your code and i can see the log

In Android: How can i send the result of from OnPostExecute() to other activity?

I got the result of OnPostExecute() to main activity but I want to use this result in second activity. I read and applied something with using Bundle but it doesn't run. I got error NullPointerException cause of not receiving the value in the second activity. Here is my MainActivity (It has an interface AsyncResponse ):
public class MainActivity extends Activity implements AsyncResponse
{
public String t;
public Bundle bnd;
public Intent intent;
public String sending;
private static final String TAG = "MyActivity";
ProductConnect asyncTask =new ProductConnect();
public void processFinish(String output){
sending=output;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
asyncTask.delegate = this;
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
bnd=new Bundle();
intent=new Intent(MainActivity.this, second.class);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
asyncTask.execute(true);
bnd.putString("veri", sending);
intent.putExtras(bnd);
startActivity(intent);
}
});
}
// START DATABASE CONNECTION
class ProductConnect extends AsyncTask<Boolean, String, String> {
public AsyncResponse delegate=null;
private Activity activity;
public void MyAsyncTask(Activity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(
"http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(t);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Please wait");
pd.setMessage("Authenticating..");
pd.show();
}
}
Here is My Second Activity:
public class second extends ActionBarActivity {
public CharSequence mTitle;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Bundle receive=getIntent().getExtras();
String get=receive.getString("veri");
Log.v(TAG, get);
}
What should i do?
AsyncTask.execute() is a non-blocking call. You can't set the result to the Bundle and start an Intent immediatly after execute(). That's why you are getting a NPE in your second Activity because sending isn't initialized, so it's null.
Move the code to start a new Activity with the desired data in your callback:
public void processFinish(String output){
bnd.putString("veri", output);
intent.putExtras(bnd);
startActivity(intent);
}
And make sure you call delegate.processFinished(String) if your data processing is finished. So move it out of the for loop. BTW t will only get the last "name"-String in the JSONArray. If you wanna get them all make t a String array and fill it.
As your variable t is globally declared in your activity so can directly use the value of t which you are assigning in your onPostExecute() method. Just you need to check for its null value only in your button click event as below :
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
asyncTask.execute(true);
if(t != null || t != "")
{
bnd.putString("veri", t);
intent.putExtras(bnd);
startActivity(intent);
}
}
});
// try this
public class MainActivity extends Activity
{
public String t;
public Bundle bnd;
public Intent intent;
private static final String TAG = "MyActivity";
ProductConnect asyncTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
bnd=new Bundle();
intent=new Intent(MainActivity.this, second.class);
asyncTask = new ProductConnect(new ResultListener() {
#Override
public void onResultGet(String value) {
bnd.putString("veri", value);
intent.putExtras(bnd);
startActivity(intent);
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
asyncTask.execute(true);
}
});
}
class ProductConnect extends AsyncTask<Boolean, String, String> {
private ResultListener target;
public ProductConnect(ResultListener target) {
this.target = target;
}
#Override
protected String doInBackground(Boolean... params) {
String result = null;
StringBuilder sb = new StringBuilder();
try {
// http post
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(
"http://192.168.2.245/getProducts.php");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
Log.d("MyApp", "Server encountered an error");
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF8"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.d("test", result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
target.onResultGet(t);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Please wait");
pd.setMessage("Authenticating..");
pd.show();
}
}
interface ResultListener {
public void onResultGet(String value);
}
}
Shortly before someone posted a solution and it works without any errors but it was deleted. This solution is by this way:
public void onClick(View arg0) {
asyncTask.execute(true);
}
});
}
Then OnPostExecute changed like this:
protected void onPostExecute(String result) {
Intent passValue=new Intent(MainActivity.this, second.class);
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
t = json_data.getString("name");
delegate.processFinish(t);
}
passValue.putExtra("veri", t);
startActivity(passValue);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
super.onPostExecute(result);
}
Lastly in my second activity receive the string by this way:
String receivedVal= getIntent().getExtras().getString("veri");
Log.v(TAG, receivedVal);
Thank you someone who posted this solution shortly before :)

Categories