passing String to AsyncTask class - java

I have the below class
public class Faculty extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "name";
static String DESIGNATION = "designation";
//static String POPULATION = "population";
static String FAC_IMG = "fac_img";
static String url;
#Override
public void onCreate(Bundle savedInstantState){
super.onCreate(savedInstantState);
// Get the view from listview_main.xml
setContentView(R.layout.faculty_list);
String data = getIntent().getStringExtra("Dpmt");
if(data.equals("DOCScience")){
url="Department%20Of%20Computer%20Science";
}
if(data.equals("DOIT")){
url="Department%20Of%20Information%20%26%20Technology";
}
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute(url);
//String url="http://192.168.170.89/bbau_faculty.php?dept="+Dept;
}
private class DownloadJSON extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Faculty.this);
// Set progressdialog title
//mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(String... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
String url1=params[0];
// Retrieve JSON Objects from the given URL address
System.out.println(url1);
jsonobject = JSONfunctions.getJSONfromURL("http://192.168.170.89/bbau_faculty.php?dept="+url1);
I am calling the DownloadJSON class
using the line
new DownloadJSON().execute(url);
In the DownloadJSON class the method
doInBackground(String... params) I want to receive the url passed in execute(url)
String url1=params[0];
But url1 is printing as null.

But url1 is printing as null.
you are doing in the correct way. If you are receinving null as value it means, in your case, that
String data = getIntent().getStringExtra("Dpmt");
is not neither DOCScience nor DOIT, and url remains initialized with with the default value (null for String declared as class member)

probably because data never equals DOCScience nor DOIT. Make sure you are getting and setting data with the correct key. Data might also be "" when setting.

Try to check url value before pass it to AsyncTask :
if(url !=null && url.trim().length()>0){
new DownloadJSON().execute(url);
}
Also use else-if leader instead of multiple if in case of check data value which either DOCScience or DOIT :
if(data.equals("DOCScience")){
url="Department%20Of%20Computer%20Science";
}else if(data.equals("DOIT")){
url="Department%20Of%20Information%20%26%20Technology";
}else{
// no match
}

Related

Blinking screen when using AsyncTask

Hey guys I know this is a common problem, Im using a AsyncTaskActivity to have a JSON parser parse some json behind the scences of a app and pump a listview with an arrayadapter. This is my code code in my mainActivity.java. My screen flickers whenever I get to the belwo activity.
setContentView(R.layout.activity_see_schedule_activity);
this.setTitle("Activity Schedule");
//Log.e("ID see schedule#",getIntent().getExtras().getString("id#"));
RequestQueue queue = Volley.newRequestQueue(see_schedule_activity.this);
StringRequest request = new StringRequest(Request.Method.POST, httpUpdateRoutines, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(see_schedule_activity.this, "" + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(see_schedule_activity.this, "Data Not Fetched " + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
//Log.e("ID see schedule#",getIntent().getExtras().getString("id#"));
map.put("residentid", getIntent().getExtras().getString("id#"));
return map;
}
};
queue.add(request);
new AsyncTaskParseJson(this).execute();
ArrayList<String> schedulelist = getIntent().getExtras().getStringArrayList("tasks_filled");
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, schedulelist);
ListView listView = (ListView) findViewById(R.id.schedulelist);
listView.setAdapter(adapter);
My AsyncTaskparseJson.java
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
private Context c;
String schedule;
String activityid;
String routine;
String[] tasks;
ArrayList<String> schedulelist = new ArrayList<String>();
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.wirelesshealth.wayne.edu/nhcheckup/getData(justin).php";
// contacts JSONArray
JSONArray dataJsonArr = null;
public AsyncTaskParseJson(Context applicationContext) {
this.c=applicationContext;
}
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
-----------------------some hash -----------------
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("schedule");
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
Log.e("doInBackground","YOU GOT HERE");
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
activityid = c.getString("activityid");
-------------------------------Pasres object c --------------
}
Intent intent = new Intent(c,see_schedule_activity.class);
-- passes back arraylist -------------- intent.putStringArrayListExtra("tasks_filled",schedulelist);
this.c.startActivity(intent);
((Activity)c).finish();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
// Intent intent = new Intent(see_schedule_activity.this,see_schedule_activity.class);
// intent.putExtra("tasks_filled",tasks);
// this.c.startActivity(intent);
// ((Activity)c).finish();
}
}
I did a bit of troubleshotting and found out the error has to do with the placement of the intent that's passed a array list. But here's the problem, if I put it in the doinBackground() the screen flashes rapidly (which is prolly becuase it keeeps calling the (setContentView(R.layout.activity_see_schedule_activity);) but if I keep it in onPostExcute nothing happens (hte arraylist isnt pumping the listview). So im a bit stumped, any help would be appreciated thanks!
As I said in my comment, you enter a recursive call between the activity and the AsyncTask as you start the same activity again with an Intent. Instead, as you already pass the activity instance to the AsyncTask, simply create an update method in the activity and use that from the AsyncTask:
// field in see_schedule_activity
private ArrayAdapter<String> adapter;
// which you'll initialize in onCreate()
// with an empty list, as you don't yet have the data
...
adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, new ArrayList<>());
ListView listView = (ListView) findViewById(R.id.schedulelist);
listView.setAdapter(adapter);
... rest of onCreate()
public void update(List<String> results) {
adapter.clear();
adapter.addAll(results);
}
Then implement correctly the AsyncTask:
public class AsyncTaskParseJson extends AsyncTask<String, Void, List<String>> {
private see_schedule_activity activity;
//... the rest
public AsyncTaskParseJson(see_schedule_activity activity) {
this.activity = activity;
}
#Override
protected List<String> doInBackground(String... arg0) {
// create scheduleList
return scheduleList;
}
#Override
protected void onPostExecute(List<String> results) {
activity.update(results);
}
//...
This is not a good implementation of the AsyncTask but should get you going.

get dynamic url with json in listview

im new programmer in android, i write program to get image url and show the image in list view, my program work correct and can show me the images but when i want to show image i should use static url, but i want to use static link to get all image url with json and show it in list view.
i have json class to get image url but i dont know how to use it in
private String imageUrls[] to get image dynamic url from my static link.
***string url is static link in mainactivity to get image url with json.
my mainactivity class:
public class MainActivity extends Activity {
private final String url="http://192.168.1.4:81/upload/images.php";
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
adapter = new LazyAdapter(this, imageUrls);
list.setAdapter(adapter);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
private String imageUrls[] = {
"http://www.technotalkative.com/wp-content/uploads/2012/09/tt_listview1-171x300.png",
"http://www.technotalkative.com/wp-content/uploads/2012/11/f-DayDream-Example-Landscape.png",
};
}
and json class:
class get url extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("login");
pd.show();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parms=new ArrayList<>();
JSONObject json=jParser.makeHTTPRequest(url,"GET");
try {
int t=json.getInt("t");
if(t==1){
s=json.getJSONArray("travel");
for(int i=0;i<s.length();i++){
String url_image=c.getString("url_image");
HashMap<String,String>map=new HashMap<String,String>();
map.put("url_image",url_image);
P.add(map);
}
}else {
Toast.makeText(MainActivity.this,"No Data Found",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
It is much more convenient to use Gson library gor parsing json response to java objects instead of extracting fields manually. It is also a good practice ( more convenient) to use Retrofit library instead of asynctasks - see https://stackoverflow.com/a/38002999/6175778 post

Android convert EditText to String [duplicate]

This question already has answers here:
Method getText() must be called from the UI Thread (Android Studio)
(5 answers)
Closed 7 years ago.
I know how to convert the EditText to a string, no clue why it doesn't work.
String username = user.getText().toString();
user = (EditText)findViewById(R.id.username);
I am getting this error: "Method getText must be called from the UI thread, currently inferred thread is worker"
Full code:
public class Login extends Activity implements OnClickListener{
private EditText user;
private Button bLogin;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://testapp.comlu.com/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
user = (EditText)findViewById(R.id.username);
String aID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
bLogin = (Button)findViewById(R.id.login);
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
// here we have used, switch case, because on login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , other than this we could also do this without switch //case.
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = user.getText().toString();
String androidID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("androidID", androidID));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Login attempt", json.toString());
// success tag for json
success = 1;
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent ii = new Intent(Login.this,Menu.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to other activity
startActivity(ii);
return json.getString(TAG_MESSAGE);
}else{
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();
}
}
}
Any ideas?
Thanks,
Yoshi
I am getting this error: "Method getText must be called from the UI
thread, currently inferred thread is worker"
you could move
String username = user.getText().toString();
in your onClick method, and pass the String to the AsyncTask like
new AttemptLogin().execute(username);
When doInBackground is invoked you can access it trough String... args, E.g. args[0]
You cannot manipulate UI elements from background thread. You are trying to access the UI element in the doInBackground method:
String username = user.getText().toString();
Instead of that, you should pass the data to the async task like:
new AttemptLogin().execute(user.getText().toString());
Also you are starting an activity from the doInBackground method. You should move that piece of code to onPostExecute method.

onPostExecute retrieves null from server

I trying read data from server by using AsyncTask, but when i give the parameter to onPostExecute, it retrieves me null.The MainActivity class:
public class MainActivity extends Activity{
EditText name, password;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView uiUpdate = (TextView) findViewById(R.id.output);
String outputasync = uiUpdate.getText().toString();
String serverURL = "http://192.168.1.105/myapp/text.php";
LongOperation longOperation = new LongOperation(MainActivity.this);
longOperation.execute(serverURL);
longOperation.onPostExecute(uiUpdate);
}
});
}
The AsyncTask:
public class LongOperation extends AsyncTask<String, Void, String> {
private Context mcontext;
private String content;
private String error = null;
AlertDialog alertDialog;
public LongOperation(Context context){
mcontext = context ;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(mcontext).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection();
client.connect();
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
client.disconnect();
} catch (IOException e) {
error = e.getMessage();
}
return null;
}
protected void onPostExecute(TextView unused) {
alertDialog.dismiss();
if (error != null) {
unused.setText("Output : " + error);
} else {
unused.setText("Output : "+ content);
}
}
}
The connectivity to server is correct, the problem is display the message inside the server in the TextView.
Upadte and solution
Like androholic said :
You should not be calling onPostExecute manually from your code. Calling execute on the asynctask should suffice. onPostExecute will automatically be called when the asynctask finishes its work.
And change the onPostExecute parameter to String
And for retrieve a TextView with the message of the server, i did what Sharj said:
2) How to set your TextView that is in your Activity. The simplest way is to pass activity variable to LongOperation constructor and use that for accessing TextView in onPostExecute.
The AsyncTask:
public class LongOperation extends AsyncTask<String, Void, String> {
TextView textviews;
private Context mcontext;
private String content;
private String error = null;
AlertDialog alertDialog;
public LongOperation(Context context, TextView textView){
textviews = textView;
mcontext = context ;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(mcontext).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection client = (HttpURLConnection)url.openConnection();
client.connect();
InputStream inputStream = client.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
content = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
client.disconnect();
} catch (IOException e) {
error = e.getMessage();
}
return null;
}
#Override
protected void onPostExecute(String unused) {
alertDialog.dismiss();
if (error != null) {
unused=("Output : " + error);
textviews.setText(unused);
} else {
unused=("Output : "+ content);
textviews.setText(unused);
}
}
The MainActivity class:
public class MainActivity extends Activity{
EditText name, password;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView uiUpdate = (TextView) findViewById(R.id.output);
String outputasync = uiUpdate.getText().toString();
String serverURL = "http://192.168.1.105/myapp/text.php";
LongOperation longOperation = new LongOperation(MainActivity.this, uiUpdate);
longOperation.execute(serverURL, outputasync);
}
});
}
Note: doInBackground still working with "return = null" because im just using it for read the data inside the server, not for retrieve it anywhere.
You should not be calling onPostExecute manually from your code. Calling execute on the asynctask should suffice. onPostExecute will automatically be called when the asynctask finishes its work.
First about the problem in your Activity:
LongOperation longOperation = new LongOperation(MainActivity.this);
longOperation.execute(serverURL);
longOperation.onPostExecute(uiUpdate);
longOperation.execute(serverURL); is an asynchronous method. Which means your program will call longOperation.onPostExecute(uiUpdate); right after execute method without waiting for the results in doInBackground.
You can't do that and you shouldn't do that. onPostExecute is automatically called after doInBackground returns result (which you return null right now.)
LongOperation longOperation = new LongOperation(MainActivity.this);
longOperation.execute(serverURL);
longOperation.onPostExecute(uiUpdate);
Now the solution:
1) doInBackground return type should always be equal to onPostExecute parameter.
If you are return String then onPostExecute will look like this:
protected void onPostExecute(String string) {
}
2) How to set your TextView that is in your Activity. The simplest way is to pass activity variable to LongOperation constructor and use that for accessing TextView in onPostExecute.
3) How to send data to onPostExecute? You have to return it in method:
#Override
protected String doInBackground(String... urls) {
// do anything here.
return "String"; //Since return type is String. You can change that you anything and make sure it matches `onPostExecute` parameter type.
}
Your doInBackground() method only returns null. Ever.
Your onPostExecute() method isn't called because it isn't overriding AsyncTask's onPostExecute() method, which would take a String argument

.execute cannot be resolved to a type - AsyncTask (Android)

im writing an app which needs to get some json from my DB, i receive the data, but now im trying to also view a icon beside the information which is shown in a listview.
The line which is making trouble is:
mChart.setTag(URL);
new DownloadImagesTask.execute(mChart); <------
MainActivity:
public class MainActivity extends Activity {
ListView list;
TextView icon;
TextView name;
TextView developer;
TextView size;
Button Btngetdata;
ArrayList<HashMap<String, String>> mList = new ArrayList<HashMap<String, String>>();
private static String url = "http://appwhittle.com/getdata.php";
private static final String TAG_ITEM = "app_item";
private static final String TAG_ICON = "app_icon";
private static final String TAG_NAME = "app_name";
private static final String TAG_DEVELOPER = "app_developer";
private static final String TAG_SIZE = "app_size";
JSONArray mJsonArray = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
icon = (TextView)findViewById(R.id.icon);
name = (TextView)findViewById(R.id.name);
size = (TextView)findViewById(R.id.size);
developer = (TextView)findViewById(R.id.developer);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
mJsonArray = json.getJSONArray(TAG_ITEM);
for(int i = 0; i < mJsonArray.length(); i++){
JSONObject c = mJsonArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
String developer = c.getString(TAG_DEVELOPER);
String icon = c.getString(TAG_ICON);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ICON, icon);
map.put(TAG_NAME, name);
map.put(TAG_DEVELOPER, "Developer: " + developer);
map.put(TAG_SIZE, size + " MB");
mList.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, mList,
R.layout.list_v,
new String[] {TAG_NAME, TAG_DEVELOPER, TAG_SIZE }, new int[] {
R.id.name, R.id.developer, R.id.size});
ImageView mChart = (ImageView) findViewById(R.id.icon);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImagesTask.execute(mChart);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+ mList.get(+position).get(TAG_NAME), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
DownloadImagesTask:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
return null;
}
}
Any help is much appreciated! Thanks in advance!
Replace
new DownloadImagesTask.execute(mChart);
with
new DownloadImagesTask().execute(mChart);
Try this. It will work.
You need to change
new DownloadImagesTask.execute(mChart);
to
new DownloadImagesTask().execute(mChart);.
Check after changing, hopefully it works fine. Happy coding :)
Change:
new DownloadImagesTask.execute(mChart);
to:
new DownloadImagesTask(mChart).execute();
You have not initialized the object of your DownloadImagesTask by calling constructor.
new DownloadImagesTask().execute(mChart); use like this. Call default constructor by putting ().
//Suppose you have a class "DataFetcher" which extends "AsyncTask<Void,Void,Void>{}"
//to execute this class write the code as follows
new DataFetcher().execute(); //done

Categories