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.
Related
This is the code I am Using.
public class MainActivity extends AppCompatActivity {
public ArrayList<String> ImageUrls = new ArrayList<>();
public ArrayList<String> ImageNames = new ArrayList<>();
public ArrayList<String> ImageDesc = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initImages();
}
private void initImages(){
final OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url("http://url.in/wp-json/wp/v2/posts?_embed")
.build();
#SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
private static final String TAG = "SlideFragment";
#Override
protected String doInBackground(Void... params) {
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
Log.d(TAG, "doInBackground: REsponse Un Successfull - 56");
return null;
}
String Data = response.body().string();
response.body().close();
return Data;
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "doInBackground: Exceptione on line63");
return null;
}
}
#Override
protected void onPostExecute(String Data) {
super.onPostExecute(Data);
if (Data != null) {
Log.d(TAG, "onPostExecute: line72");
try {
JSONArray json = new JSONArray(Data);
for (int i = 0; i < json.length(); i++) {
JSONObject post = json.getJSONObject(i);
String title = post.getJSONObject("title").getString("rendered");
String description = post.getJSONObject("content").getString("rendered");
String imgURL = post.getJSONObject("_embedded").getJSONArray("wp:featuredmedia").getJSONObject(0).getJSONObject("media_details").getString("file");
String imagUrl = "http://url.in/wp-content/uploads/" + imgURL;
ImageNames.add(title);
ImageDesc.add(description);
ImageUrls.add(imagUrl);
Log.d(TAG, "onPostExecute: " + ImageNames);
}
}catch(JSONException j){
j.printStackTrace();
Log.d(TAG, "onPostExecute: on line 121");
}
}
}
};
asyncTask.execute();
initRecycler();
}
private void initRecycler(){
RecyclerViewPager mRecyclerView = (RecyclerViewPager) findViewById(R.id.list);
// setLayoutManager like normal RecyclerView, you do not need to change any thing.
LinearLayoutManager layout = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
mRecyclerView.setLayoutManager(layout);
//set adapter
//You just need to implement ViewPageAdapter by yourself like a normal RecyclerView.Adpater.
RecyclerViewAdapter adapter = new RecyclerViewAdapter(ImageUrls, ImageNames, ImageDesc, this);
mRecyclerView.setAdapter(adapter);
}
}
I have run the same code with local data i..e the ArrayList with hardcoded data. It works. But If I try with API data It shows Nothing. I have checked the ArrayList with logging. It is fine.
I don't know where I am Wrong.
UPDATE
Thanks to #sonhnLab. In the code I have removed initRecycler(); from initImages(); and added to onPostExecute();. That worked.
Due to the asynchronous nature of Asynctask, the following line: "initRecycler();" doesn't necessarily gets called after completion of the network request hence no content. Remember, any task that depends on the asynchronous response needs to be implemented inside response method, in this case inside onPostExecute().
With the Help of sonhnlab I have successfully got the desired output.
I have made this initRecycler(); call into onPostExecute() call. so when the information is ready from the API call it initiates the Recycler.
I have Updating the Code in the question.
You should call initRecyler() onPostExecute when async task is completed
what I do in this code for comparing retrieved data from server to other string, please tell me changes.
ArrayList<HashMap<String, String>> matchStudentsList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third_sem);
present = (Button) findViewById(R.id.button2);
bt= BluetoothAdapter.getDefaultAdapter();
// Call Async task to get the match fixture
new GetFixture().execute();
}
private class GetFixture extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
ServiceHandler serviceClient = new ServiceHandler();
Log.d("url: ", "> " + URL_Students);
String json = serviceClient.makeServiceCall(URL_Students,ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture response: ", "> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchRecords = jsonObj.getJSONArray(TAG_Table);
Log.d("json aray", "user point array");
int len = matchRecords.length();
Log.d("len", "get array length");
for (int i = 0; i <len; i++) {
JSONObject c = matchRecords.getJSONObject(i);
String RollNo = c.getString(TAG_Roll_No);
Log.d("RollNo", RollNo);
String FirstName = c.getString(TAG_First_Name);
Log.d("FirstName", FirstName);
String LastName = c.getString(TAG_Last_Name);
Log.d("LastName", LastName);
// hashmap for single match
HashMap<String, String> matchFixture = new HashMap<String, String>();
// adding each child node to HashMap key => value
matchFixture.put(TAG_Roll_No, RollNo);
matchFixture.put(TAG_First_Name, FirstName);
matchFixture.put(TAG_Last_Name, LastName);
matchStudentsList.add(matchFixture);
}
}
catch (JSONException e) {
Log.d("catch", "in the catch");
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
ThirdSem.this, matchStudentsList,
R.layout.list_checkitem, new String[]{TAG_Roll_No, TAG_First_Name, TAG_Last_Name, TAG_BAddress}
, new int[]{R.id.RollNo, R.id.FirstName, R.id.LastName }
);
setListAdapter(adapter);
}
}
}
it will be very very helpful for me please
You are returning a null value on all your if statements, you should return matchStudentsList once you are done with your for loop, otherwise return null
after your for loop , add:
return matchStudentsList;
and change your onPostExecute signature to:
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
also change your AsyncTask definition to:
AsyncTask<String, Void, ArrayList<HashMap<String, String>>>
You can get your doInBackground() string by something like this.
String desiredString = new GetFixture().execute().get();
Call the above in onCreate() method. Instead of :
new GetFixture().execute();
Ejects the following error when the application is run, I have two classes one ListViewAdapter other is JSONFunctions? What is a mistake, maybe it's my URL? my URL to the API 77.105.36.203/api/v1/info or problem is function doInBackgoround JSONObject?
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID = "id";
static String IME = "ime";
static String ADRESA = "adresa";
static String SLIKA = "slika";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listview_main, container, false);
new DownloadJSON().execute();
return rootView;
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// 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(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://77.105.36.203/api/v1/info");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("objects");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id", jsonobject.getString("id"));
map.put("ime", jsonobject.getString("ime"));
map.put("adresa", jsonobject.getString("adresa"));
map.put("slika", jsonobject.getString("slika"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) getView().findViewById(R.layout.listview_item);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
This is error log.
07-10 16:15:59.605: E/log_tag(5389): Error parsing data [Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject]07-10 16:15:59.605: E/AndroidRuntime(5389): FATAL EXCEPTION: AsyncTask #2
Check this code in your doInBackground() method, and tell me if works.
try {
// Locate the array name in JSON
//jsonarray = jsonobject.getJSONArray("objects");
JSONObject jsonObject = jsonobject.getJSONObject("objects");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
//jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id", jsonObject.getString("id"));
map.put("ime", jsonObject.getString("ime"));
map.put("adresa", jsonObject.getString("adresa"));
map.put("slika", jsonObject.getString("slika"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
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
I am using achartEngine to draw linechart in my android application. I am setting data in the code. Now I need to get data from JSON and display it in my graphics, but I don't know how to connect my JSON with achartengine and display it into linechart.
This is my wrong source code :
parsing json
public class ErizaChartEngine extends Activity {
List NabList = new ArrayList();
boolean statuskoneksi= true;
private ProgressDialog Dialog;
protected Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new LineChartAsyncTask().execute();
setContentView(R.layout.layoutchart);
}
public class LineChartAsyncTask extends AsyncTask <String, String, String>{
#Override
protected void onPreExecute (){
super.onPreExecute();
Dialog=new ProgressDialog(ErizaChartEngine.this);
Dialog.setMessage("Mohon Tunggu Sebentar...");
Dialog.setIndeterminate(false);
Dialog.setCancelable(true);
Dialog.show();
}
#Override
protected String doInBackground(String... params) {
String url= "http://www.ab.com/NabChart.htm?id=03&nilai=10";
try {
JSONParser jp= new JSONParser();
JSONArray ja= jp.takeJson(url);
for (int i=0; i<ja.length();i++){
JSONObject jo = ja.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
if (jo.has("lnu_nilai"))
map.put("lnu_nilai", jo.get("lnu_nilai").toString());
if (jo.has("tanggal"))
map.put("tanggal", jo.get("tanggal").toString());
NabList.add(map);
System.out.println("json parser done");
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
Dialog.dismiss();
}
This is my class for drawing graphics :
public void drawNABContentSimpleChart
(
String strtanggal,
String strNilaiNABHMin0)
{
XYSeries nabseries = new XYSeries("nab");
for (int i=0;i<NabList.size();i++){
nabseries.add(strNilaiNABHMin0[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
// Adding Income Series to the dataset
dataset.addSeries(nabseries);
XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
incomeRenderer.setColor(Color.WHITE);
incomeRenderer.setPointStyle(PointStyle.CIRCLE);
incomeRenderer.setFillPoints(true);
incomeRenderer.setLineWidth(2);
incomeRenderer.setDisplayChartValues(true);
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setXLabels(0);
multiRenderer.setChartTitle("NAB 1 year");
multiRenderer.setXTitle("Year 2012");
multiRenderer.setYTitle("Nilai");
multiRenderer.setZoomButtonsVisible(true);
for(int i=0;i<NabList.size();i++){
multiRenderer.addXTextLabel(strtanggal[i]);
}
multiRenderer.addSeriesRenderer(incomeRenderer);
// multiRenderer.addSeriesRenderer(expenseRenderer);
// Creating an intent to plot line chart using dataset and multipleRenderer
Intent intent = ChartFactory.getLineChartIntent(getBaseContext(), dataset, multiRenderer);
// Start Activity
startActivity(intent);
}
I really need help to solve my problem, because my code still wrong and I don't know how to fix it. is there anyone can help me to solve this?
Just initialize the chart stuff (dataset, renderer) and start parsing your json. Add every data item you read from the file to your series in the dataset. Once you are done, display the chart.