I've got my main startup class loading MainActivity but I'm trying to figure out how to access the TextView from another class which is loading information from a database. I would like to publish that information to the TextView.
private class DateValidation extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog
}
#Override
protected String doInBackground(String... arg0) {
String hallId = arg0[0];
String date = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?id=" + URLEncoder.encode(hallId, "UTF-8");
data += "&date=" + URLEncoder.encode(date, "UTF-8");
link = "https://www.adoetech.co.tz/ehall/frontend/index.php/hall/validate-date" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
Log.d("postData: ", link);
return result;
} catch (Exception e) {
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject jsonObj = new JSONObject(result);
boolean query_result = jsonObj.getBoolean("success");
String response = jsonObj.getString("data");
if (query_result) {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_LONG).show();
} else if (!query_result) {
Log.d("onPostExecute: ", "free");
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
//JSONArray dateVal = jsonObj.getJSONArray("data");
I need to setTest from here and I have declear hallPrice from MainActivity help Please
hallPrice.setText("300000000");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("onPostExecute: ", String.valueOf(result));
Toast.makeText(HallsDetails.this, "Error parsing JSON data.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HallsDetails.this, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Use intent to pass data from one activity to another like this:-
Intent in = new Intent(MainActivity.this, DateValidation.class);
in.putExtra("key", "300000000");
startActivity(in);
And in your DateValidation Activity do:-
Intent i = getIntent();
String value = i.getStringExtra("key");
hallPrice.setText(value);
You can pass the TextView in your AsyncTask.
public class DateValidation extends AsyncTask<String,String,String> {
TextView mTextView;
public DateValidation (TextView textView){
mTextView = textView;
}
#Override
protected String doInBackground(String... strings) {
/**
* do process here
*/
return "Result String here";
}
#Override
protected void onPostExecute(String result) {
mTextView.setText(result);
}
}
Related
I am trying to get data from a JSON file that was written in a PHP file which was stored in my online hosting server(00webhost.com). When I run my program it says unknown host. However, the address will give JSON formatted file.
I have all the permissions along with the internet permission in my AndroidManifest.xml file.
Activity Class :
public class Recmain extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
private List<movie> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private moviesadapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rmain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
String m=intent.getStringExtra("data");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new moviesadapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
}
private void prepareMovieData(){
movie movie = new movie("Mad Max: Fury Road", "Action & Adventure",
"2015");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(recmain.this,url,Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser sh = new JSONParser();
// Making a request to url and getting response
String url = "https://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("id");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
Toast.makeText(getApplicationContext(), id ,
Toast.LENGTH_LONG).show();
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat
for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Adapter class:
public class JSONParser {
private static final String TAG = JSONParser.class.getSimpleName();
public JSONParser() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
It says, unknown host.
Looks like the URL is not formatted correctly. I think there is a space between the two parts of the URL.
private static String url = "http://tongue-tied-papers.000webhostapp.com/data_fetch.php"
Please try with the URL above without any space between the tied- and papers. You have two separate URL declaration, one at the beginning of the class and the other is in the doInBackground method. Please try changing both.
I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}
This is my first time with getting APIS to return the result JSON object. I think I have got the async task code right but I just don't know how to execute it. This is my class code.
For my layout all I have is one button with an onClick () method gg, a progress bar and one text view.
This is the async task:
public class MainActivity extends Activity
{
ProgressBar progressBar;
TextView responseView;
EditText emailText;
String URL;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
responseView = (TextView) findViewById(R.id.responseView);
emailText = (EditText) findViewById(R.id.emailText);
URL = "https://kgsearch.googleapis.com/v1/entities:search?query=taylor+swift&key=APIKEY&limit=1&indent=True";
}
public void gg(View v)
{
new RetrieveFeedTask.execute();
}
private class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
responseView.setText("");
Toast.makeText(MainActivity.this, "pre execute", Toast.LENGTH_LONG).show();
}
protected String doInBackground(Void... urls) {
String email = emailText.getText().toString();
// Do some validation here
try {
URL url = new URL(URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
Toast.makeText(MainActivity.this, "post execute", Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
}
}
}
So in the public void gg(View v)
I call the .execute method but it gives me an error
Unknown type execute
Do I have to add some params to the execute method?
If so what?
Thanks.
Try
new RetrieveFeedTask().execute();
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
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 :)