I'm using URLEncoder in my activity. but i have a error in MyTask. I have marked the error with Error in my code.
public class Search_Ringtone extends SherlockActivity{
ListView lsv_latest;
List<ItemRingCategoryItem> arrayOfRingcatItem;
RingCateItemAdapter objAdapterringitemitem;
AlertDialogManager alert = new AlertDialogManager();
private ItemRingCategoryItem objAllBean;
JsonUtils util;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ringcatitem_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
lsv_latest=(ListView)findViewById(R.id.latest_list);
arrayOfRingcatItem=new ArrayList<ItemRingCategoryItem>();
if (JsonUtils.isNetworkAvailable(Search_Ringtone.this)) {
String str = Constant.SEARCH_RINGTONE_URL+Constant.SEARCH.replace(" ", "%20");
String myUrl = URLEncoder.encode(str, "UTF-8");
MyTask().execute(myUrl); //*Error*
} else {
showToast("No Network Connection!!!");
alert.showAlertDialog(Search_Ringtone.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
}
lsv_latest.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
objAllBean=arrayOfRingcatItem.get(position);
Intent intplay=new Intent(getApplicationContext(),SingleRingtone.class);
Constant.RINGTONE_ITEMID=objAllBean.getRingItemId();
startActivity(intplay);
}
});
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Search_Ringtone.this);
pDialog.setMessage("لطفا صبر کنید...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Server Connection Error");
alert.showAlertDialog(getApplicationContext(), "Server Connection Error",
"May Server Under Maintaines Or Low Network", false);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.LATEST_ARRAY_NAME);
JSONObject objJson = null;
if(jsonArray.length()==0)
{
showToast("موردی پیدا نشد!");
}
else
{
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemRingCategoryItem objItem = new ItemRingCategoryItem();
objItem.setRingItemId(objJson.getString(Constant.CATEITEMRING_RINDID));
objItem.setRingItemCatId(objJson.getString(Constant.CATEITEMRING_RINDCATID));
objItem.setRingItemCatName(objJson.getString(Constant.CATEITEMRING_CATENAME));
objItem.setRingItemName(objJson.getString(Constant.CATEITEMRING_RINGNAME));
objItem.setRingItemUrl(objJson.getString(Constant.CATEITEMRING_RINDURL));
objItem.setRingItemDownCount(objJson.getString(Constant.CATEITEMRING_RINDDOWNCOUNT));
objItem.setRingItemUser(objJson.getString(Constant.CATEITEMRING_RINDUSER));
objItem.setRingItemTag(objJson.getString(Constant.CATEITEMRING_RINDTAG));
objItem.setRingItemSize(objJson.getString(Constant.CATEITEMRING_RINDSIZE));
objItem.setRingStar(objJson.getString(Constant.LATESTRING_RINGSTAR));
objItem.setRingImage(objJson.getString(Constant.LATESTRING_RINGIMAGE));
arrayOfRingcatItem.add(objItem);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
Shouldn't it be new MyTask().execute(myURL);?
Also because it's an AsyncTask you need to retain a reference to it until it's finished or else the garbage collector destroys it.
i write like this and solved thank you everyone:
if (JsonUtils.isNetworkAvailable(Search_Ringtone.this)) {
String str = Constant.SEARCH_RINGTONE_URL+Constant.SEARCH.replace(" ", "%20");
String myUrl = null;
try {
myUrl = URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MyTask().execute(myUrl);
Related
What could be the reason why I am getting that kind of error? I have looked already for possible solutions for my problem, but I couldn't find one.
Here is the code:
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem) {
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(ShowSingleRecordActivity.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
NameHolder = jsonObject.getString("name").toString() ;
SurnameHolder = jsonObject.getString("surname").toString() ;
AddressHolder = jsonObject.getString("address").toString() ;
ContactnoHolder = jsonObject.getString("contactno").toString() ;
UsernameHolder = jsonObject.getString("username").toString() ;
PasswordHolder = jsonObject.getString("password").toString() ;
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
NAME.setText(NameHolder);
SURNAME.setText(SurnameHolder);
ADDRESS.setText(AddressHolder);
CONTACTNO.setText(ContactnoHolder);
USERNAME.setText(UsernameHolder);
PASSWORD.setText(PasswordHolder);
}
}
Ok, I have a custom view which plays gifs from the internet. Therefor I need to add an url to my view to download the gif. But I can't seem to update my custom view inside my asynctask. I need to add an url string to my custom view gifView.setUrl(). It works in the onCreate Class but it gives me null in asynctask.
Oncreate class
GifView gifView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
id = extras.getInt("id");
String idStr = String.valueOf(id);
String extension = extras.getString("extension");
if(extension.equals(".gif")){
setContentView(R.layout.activity_post_gif);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gifView = (GifView)findViewById(R.id.gifview);
titleStr = (TextView)findViewById(R.id.titleTXT);
postInfo = (TextView)findViewById(R.id.infoTXT);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//the url
new getJsonInfoGif().execute("http://www.website.com/jsonApi");
}else{
Asynctask
public class getJsonInfoGif extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("loading post...");
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
return GET(strings[0]);
}
#Override
protected void onPostExecute(String res) {
try {
JSONObject jsonObject = new JSONObject("{'postinfo':[" + res + "]}");
JSONArray jsonArray = jsonObject.getJSONArray("postinfo");
JSONObject obj = jsonArray.getJSONObject(0);
//post title
titleStr.setText(obj.getString("name"));
//category and maker full name
//large image
JSONObject imgObj = obj.getJSONObject("thumbnails");
gifView.setUrl("http://www.website.com/my.gif");
} catch (JSONException e) {
e.printStackTrace();
}
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
GifView.java
public void setUrl(String urlStr){
this.urlStr = urlStr;
invalidate();
requestLayout();
}
public String getUrl(){
return this.urlStr;
}
public void init(final Context context)throws IOException{
setFocusable(true);
movie = null;
movieWidth = 0;
movieHeight = 0;
movieDuration = 0;
final Thread thread = new Thread(new Runnable() {
#Override
public void run(){
try{
Log.d("DEBUG", "URL" + urlStr);
URL url = new URL(urlStr);
try {
HttpURLConnection http = (HttpURLConnection) url.openConnection();
inputStream = http.getInputStream();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
movie = Movie.decodeStream(inputStream);
movieWidth = movie.width();
movieHeight = movie.height();
movieDuration = movie.duration();
((PostActivity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
invalidate();
requestLayout();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}
});
thread.start();
}
Here is the Log from the url, it gives me null if I add the url inside my asynctask in Activity.
11-07 14:41:58.821 5674-6076/svenmobile.tools.showcase D/DEBUG﹕ URLnull
What I want to know is what the problem is and how to solve it if possible.
Thanks in advance, Sven
Maybe you called init() before setUrl().
You can pass it the url in the contructor, or public void init(final Context context, String urlStr)throws IOException{
I also suggest you to move all that network code to doInBackground
I want to use pagination for a listview in android.I am loading 10 values at a time from a web service.But the problem is that the group of 10 values keep repeating.I have used an array list called ice_data for the adapter of the listview.The code:
public class VideoActivity extends Activity {
private ConnectionDetector cd;
public HttpResponse video_respons;
public String video_string_response1;
public ArrayList<NameValuePair> nameValuePairs_Video;
ArrayList<Ice_data> ice_list;
String URL="http://footballultimate.com/icebucket/index.php/api/getVideo";
String URL1="http://footballultimate.com/icebucket/index.php/api/getVideoByLimit";
JSONObject jsonobj;
JSONArray jsonarr;
Ice_data iceobj;
CustomIceAdapter ciadp;
ListView list;
int start = 1;
int limit = 10;
boolean loadingMore = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
ice_list=new ArrayList<Ice_data>();
// GEt all Data for Video
cd = new ConnectionDetector(VideoActivity.this);
Config.isInternetPresent = cd.isConnectingToInternet();
if (!Config.isInternetPresent) {
AlertDialog.Builder builder = new AlertDialog.Builder(VideoActivity.this);
// Shuld be fail icon
builder.setIcon(R.drawable.ic_launcher);
builder.setMessage("Connection Not Available !" + "\n"
+ "Please enable your Internet Connection");
builder.setTitle("INTERNET CONNECTION");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
new GetVideos().execute();
}
// Get all Data for Video
list= (ListView) findViewById(R.id.videoList);
list.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
new GetVideos().execute();
}
}
});
}
class GetVideos extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
private HttpResponse vip_respons;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(VideoActivity.this);
pDialog.setTitle("Processing...");
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
loadingMore = true;
//ice_list=new ArrayList<Ice_data>();
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL1);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("start",String.valueOf(start)));
nameValuePairs.add(new BasicNameValuePair("limit",String.valueOf(limit)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
video_respons = httpclient.execute(httppost);
//video_string_response1 = getResponseBody(video_respons);
video_string_response1=responsetostring.getResponseBody(video_respons);
//Log.d("Store_Response", the_string_response1);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String video_string) {
try{
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
catch(Exception e){
e.printStackTrace();
}
finally
{
pDialog.dismiss();
}
if (video_string_response1!=null) {
//displayjsonstring();
geticevalues(video_string_response1);
}
}
}
public void geticevalues(String result)
{
try {
jsonobj=new JSONObject(result);
//ice_list=new ArrayList<Ice_data>();
jsonarr=jsonobj.getJSONArray("video_data");
for(int i=0;i<jsonarr.length();i++)
{
JSONObject jso=jsonarr.getJSONObject(i);
iceobj=new Ice_data();
iceobj.title=jso.getString("title");
iceobj.image_URL=jso.getString("image");
iceobj.video_URL=jso.getString("url");
ice_list.add(iceobj);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ciadp=new CustomIceAdapter(VideoActivity.this,ice_list);
loadingMore = false;
ciadp.notifyDataSetChanged();
list.setAdapter(ciadp);
start+=10;
}
How do i prevent the duplication of the values in the listview.?
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 :)