trouble loading JSON in AsyncTask in Fragment - android

I got 3 swipeable empty Views. The 3rd View is the "ViewAll". The first View works fine but when I swipe to the second it shows this error.
I've tried to display data that I loaded with JSON in a AsyncTask, but there is this NullPointerException error
and I don't know how to solve it...
11-12 10:00:23.046: E/InputEventReceiver(12007): Exception dispatching input event.
11-12 10:00:23.046: E/MessageQueue-JNI(12007): Exception in MessageQueue callback: handleReceiveCallback
11-12 10:00:23.056: E/MessageQueue-JNI(12007): java.lang.NullPointerException
11-12 10:00:23.056: E/MessageQueue-JNI(12007): at com.example.rumorz.ViewAll$PostTask.onPreExecute(ViewAll.java:52)
11-12 10:00:23.056: E/MessageQueue-JNI(12007): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
Here is my code:
public class ViewAll extends Fragment {
//URL to get JSON Array
private static String url = ""; //URL to my site with JSON-code
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_message= "message";
TextView tvuser ;
TextView tvmessage ;
JSONArray user = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
new PostTask().execute();
View rootView = inflater.inflate(R.layout.viewall, container, false);
return rootView;
}
private class PostTask extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
tvuser = (TextView)getView().findViewById(R.id.tvUser);
tvmessage = (TextView)getView().findViewById(R.id.tvmessage);
}
#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) {
try {
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String users = c.getString(TAG_USER);
String message = c.getString(TAG_message);
tvuser.setText(users);
tvmessage.setText(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

onPreExecute(), invoked on the UI thread immediately after the task is executed.
intialize
tvuser = (TextView)rootView.findViewById(R.id.tvUser);
tvmessage = (TextView)rootview.findViewById(R.id.tvmessage);
in onCreateView

Initialize it in onCreateView. Use the inflated view object to initialize your textview's. or use getView in onActivityCreated to initialize textview's.
Since the textview is declared as a class member you can use it in onPostEecute to set text to the same.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.viewall, container, false);
tvuser = (TextView)rootView.findViewById(R.id.tvUser);
tvmessage = (TextView)rootview.findViewById(R.id.tvmessage);
new PostTask().execute();
return rootView;
}

Related

Personality Insight Error

FATAL EXCEPTION: main
Process: com.example.dell.ora, PID: 24491
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.squareup.okhttp.Dns$1.lookup(Dns.java:39)
at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.squareup.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.squareup.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.squareup.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.squareup.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.squareup.okhttp.Call.getResponse(Call.java:286)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:243)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:205)
at com.squareup.okhttp.Call.execute(Call.java:80)
at com.ibm.watson.developer_cloud.service.WatsonService.execute(WatsonService.java:122)
at com.ibm.watson.developer_cloud.service.WatsonService.executeRequest(WatsonService.java:183)
at com.ibm.watson.developer_cloud.personality_insights.v2.PersonalityInsights.getProfile(PersonalityInsights.java:119)
at com.example.dell.ora.AnalyzerFragment.onCreateView(AnalyzerFragment.java:39)
I am trying to run personality insight from checking the docs I have this in my fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View x = inflater.inflate(R.layout.fragment_analyzer, container, false);
PersonalityInsights service = new PersonalityInsights();
service.setUsernameAndPassword("", "");
service.setEndPoint("https://gateway.watsonplatform.net/personality-insights/api");
EditText content= x.findViewById(R.id.content);
TextView output= x.findViewById(R.id.output);
// String text = content.getText().toString();
String text =getResources().getString(R.string.demo);
Profile profile = service.getProfile(text);
System.out.println(profile);
return x;
}
And to do this I inserted in my gradle file
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.ibm.watson.developer_cloud:java-sdk:2.10.0'
Has anybody encountered this error?Can sb make evident what am I making wrong?Thank You in advance!
new Thread(new Runnable(){Profile profile = service.getProfile(text);
}).start();
Or use an async task. You must only initialize layouts and Views in your onCreateView. All other object initializations must be done in your onActivityCreated
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
final String text =getResources().getString(R.string.demo);
new AsyncTask<Void, Void, Void>() {
#Override
protected Profile doInBackground(Void... params) {
PersonalityInsights service = new PersonalityInsights();
service.setUsernameAndPassword("", "");
service.setEndPoint("https://gateway.watsonplatform.net/personality-insights/api");
Profile profile = service.getProfile(text);
return profile;
}
#Override
protected void onPostExecute(Profile profile) {
super.onPostExecute(profile);
TextView output = x.findViewById(R.id.output);
output.setText(profile.toString())
}
}.execute();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View x = inflater.inflate(R.layout.fragment_analyzer, container, false);
EditText content= x.findViewById(R.id.content);
TextView output = x.findViewById(R.id.output);
// String text = content.getText().toString();
return x;
}

null object reference on fragment new instance

I want to run an instance of fragment from activity. But it returns error null object reference.
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.mani.view.StaggeredGridView.addItem(com.mani.view.StaggeredGridViewItem)' on a null object reference
at com.example.myapp.FavouriteListFragment.onCreateView(FavouriteListFragment.java:57)
When i debug, this line shows null pointer error
mStaggeredView.addItem(item);
debug result shows that fragmentClass is null value. It does not works well now after I have added inheritance class in my fragment. Here is my fragment
public class FavouriteListFragment extends Fragment {
public static final String ARG_ITEM_ID = "favorite_list";
private SharedPreference sharedPreference;
private StaggeredGridView mStaggeredView;
TextView tv;
ImageView iv;
String text;
String favouriteUrl;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_favourite_staggeredgridview, container, false);
sharedPreference = new SharedPreference();
iv=(ImageView)rootView.findViewById(R.id.imageView);
text = sharedPreference.getValue(getActivity());
sharedPreference.saveFavourite(getActivity(), text);
String[] photoUrl;
photoUrl = new String[10];
for (int index = 0; index < photoUrl.length; index++) {
photoUrl[index]=text;
StaggeredGridViewItem item = null;
item = new FavouriteGridItem(getActivity(),photoUrl); //pass one image of index
mStaggeredView.addItem(item);
}
URL url = null;
try {
url = new URL(text);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
iv.setImageBitmap(bmp);
return rootView;
}
}
This line is one of your problems:
mStaggeredView.addItem(item);
From the code you posted it is logical that you get a nullpointer on mStaggeredView.addItem() because you did not assign anything to mStaggeredView. You must do something like mStaggeredGridView = (StaggeredGridView) rootView.findViewById(R.id.some_id) somewhere

Can not access “findViewById” in AsyncTask

https://stackoverflow.com/a/14164318/3575963
Here, he used
View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
From parent class. Also I don't have inflater in my parent, it is a map.
And from asynctask doitbackground, I returned 5 arraylists to make textview in postexecute.
But I can't do because I can't use findviewbyid because I can't get activity. I got context but it does not do anything.
Here is my postexecute
protected void onPostExecute(Wrapper wrap){
TextView name = new TextView (mContext);
TextView type = new TextView (mContext);
TextView location = new TextView (mContext);
TextView distance = new TextView (mContext);
List<Double> dist = new ArrayList();
List<String> loc = new ArrayList();
List<String> nme = new ArrayList();
List<String> typ = new ArrayList();
List<Calendar> start = new ArrayList();
List<Calendar> endd = new ArrayList();
dist = wrap.getDist();
loc = wrap.getLocation();
nme = wrap.getName();
typ = wrap.getType();
start = wrap.getsDate();
endd = wrap.geteDate();
int idx = -1;
LinearLayout shw_evnt = (LinearLayout) shw_evnt.findViewById(R.id.);
for(Double dis:dist){
idx++;
name.setText(nme.get(idx));
type.setText(typ.get(idx));
location.setText(loc.get(idx));
distance.setText(dist.get(idx).toString()+" meters");
This part is faulty
LinearLayout shw_evnt = (LinearLayout) shw_evnt.findViewById(R.id.);
I tried other things but it did not work. I will use another layout that was not used before.
show_events.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
android:id="#+id/shwevnt"
</LinearLayout>
Here caller mapactivity class
public class MapActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private int strokeColor = 0xffff0000; //red outline
private int shadeColor = 0x44ff0000; //opaque red fill
private int count=0;
private GoogleMap googleMap;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private Context mContext;
private String TAG = "Chic";
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private int radius;//in meters
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "inside map oncreaste");
mContext = getApplicationContext();
View myFragmentView = inflater.inflate(R.layout.show_events, container, false);
super.onCreate(savedInstanceState);
setUpMapIfNeeded();
Log.d(TAG, "buildgoogleapi called");
buildGoogleApiClient();
Log.d(TAG, "after buildgoogleapi called");
}//end of oncreate
here error on that
View myFragmentView = inflater.inflate(R.layout.show_events, container, false);
because i dont have inflater
I dont want to return from postexecute to main class or another wrapper class. I think i can do inside postexecute, cant i?
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
if i do this, i will take current view, not the view i want to create?
I tried
private Inflater inflater;
View myFragmentView = inflater.inflate(R.layout.show_events, container, false);
Yep, just pass the Activity to the Asynctask:
AsyncTask myAsyncTask = new MyTask(this);
And then you will find the element inside the layout of the Activity:
public class MyTask extends AsyncTask<String, String, String>{
public MyActivity activity;
public MyTask(MyActivity a){
this.activity = a;
}
protected void onPostExecute(String result){
...
...
LinearLayout shw_evnt = (LinearLayout) activity.findViewById(R.id.shwevnt);
...
...
}
}
Like Daniel describes it would be a bad practice.
I recommend to you an Interface.
for example:
a) Create interface class.
public interface AsyncResponse {
void processFinish(String output);
}
b) Go to your AsyncTask class, and declare interface AsyncResponse as a field :
public class MyAsyncTask extends AsyncTask{
public AsyncResponse delegate = null;
#Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
}
c) In your main Activity you need to implements interface AsyncResponse.
public class MainActivity implements AsyncResponse{
MyAsyncTask asyncTask =new MyAsyncTask();
#Override
public void onCreate(Bundle savedInstanceState) {
//this to set delegate/listener back to this class
asyncTask.delegate = this;
//execute the async task
asyncTask.execute();
}
//this override the implemented method from asyncTask
void processFinish(String output){
//Here you will receive the result fired from async class
//of onPostExecute(result) method.
LinearLayout shw_evnt = (LinearLayout) findViewById(R.id.shwevnt);
}
}
this is the solution..
facturas_edittext=(EditText)((Activity)context).findViewById(R.id.mye);
Just pass the Activity as a parameter to the AsyncTask class. See here. Note that its bad practice to store context as a member variable since the context may change.

Executing method inside fragment

I am receiving a warning when trying to execute a method inside a Fragment.
public class PrimaryFragmentDormir extends Fragment {
// Declare Variables
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
ListViewAdapter adapter;
private List<WorldPopulation> worldpopulationlist = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_dormir,null);
// Get the view from listview_main.xml
// setContentView(R.layout.listview_main);
// Execute RemoteDataTask AsyncTask
issue here==> new RemoteDataTask.execute();
//test commit dell
}
// RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Parse.com Custom ListView Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
worldpopulationlist = new ArrayList<WorldPopulation>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Country");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("ranknum");
ob = query.find();
for (ParseObject country : ob) {
// Locate images in flag column
ParseFile image = (ParseFile) country.get("flag");
WorldPopulation map = new WorldPopulation();
map.setRank((String) country.get("rank"));
map.setCountry((String) country.get("country"));
map.setPopulation((String) country.get("population"));
map.setFlag(image.getUrl());
worldpopulationlist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) getView().findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(PrimaryFragmentDormir.this.getActivity(),
worldpopulationlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
I have searched for a solution, but I am not able to solve the issue.
Thank you
Is it me or your code cannot compile because the line
new RemoteDataTask.execute();
cannot be reached ? It's right after a return.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_dormir,null);
// ...
new RemoteDataTask.execute();
}
Secondly, as it has been mentioned, you need parenthesis to create a new object :
new RemoteDataTask().execute();
Try something like this :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
new RemoteDataTask().execute();
return inflater.inflate(R.layout.primary_layout_dormir,null);
}
Your syntax is a little off here:
new RemoteDataTask.execute();
When you instantiate an object with new, you need parenthesis like so: new RemoteDataTask().
Your error says "cannot resolve symbol 'execute'", because the execute() method doesn't exist as a static method on the RemoteDataTask class, and even if it did it wouldn't work with the new operator.
Thus you want to change that line to:
new RemoteDataTask().execute();

AsyncTask Fragment Rotation

I have a listview inside a fragment showing weather data(image,temperature and weather description). I fetch the data from here
When I rotate the emulator though I get a crash.:(. Here is my code. I use the setRetainedInstance but with out any result. Somehow I need to save and restore the asynchronous data I get,but I don't know how.
public class ForecastFragment extends Fragment{
ListView listView;
List<WeatherForecastData> WeatherForecastDataList;
String IMG_URL = "http://api.openweathermap.org/img/w/";
Fragment fragment;
public ForecastFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflate xml view and convert it to a View object
View rootView = inflater.inflate(R.layout.fragment_forecast, container, false);
//Initialise ListView.
listView = (ListView) rootView.findViewById(R.id.listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String temp = WeatherForecastDataList.get(position).getWeatherTemperature();
Toast.makeText(getActivity(),temp+" Have a nice day",Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
//Now we are ready for further processing
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
requestData("http://api.openweathermap.org/data/2.5/forecast/daily?lat=50.09&lon=14.42&cnt=9&&units=metric&mode=json");
}
//We create a MyTask object,and execute the async. thread with the specified url which is shown just above.
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
//AsyncTask that will do the asynchronous threading. It displays the weather's icon,description
//and temperature in the main thread via the OnPostExecute(...) method.
private class MyTask extends AsyncTask<String, String, List<WeatherForecastData>> {
#Override
protected void onPreExecute() {
//Used to initialise Views such as Progress Bars which are not needed for this
//project.
}
#Override
protected List<WeatherForecastData> doInBackground(String... params) {
//Read the url,specify the METHOD GET, and store it in content.
String content = HttpManager.getData(params[0]);
//JSON parsing of the openweather api's response. It is not hard,but I had to use the
//debugger quite a lot to make sure that I deserialise the correct JSON values into Strings.
WeatherForecastDataList = WeatherJSONParser.parseFeed(content);
//Fetching the url image
for (WeatherForecastData d : WeatherForecastDataList) {
try {
String imageUrl = IMG_URL +d.getPhoto();
InputStream in = (InputStream) new URL(imageUrl).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(in);
//Is it deprecated?
d.setBitmap(bitmap);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return WeatherForecastDataList;
}
//WeatherForecastData is the Object that contains all that instances we want to display.
#Override
protected void onPostExecute(List<WeatherForecastData> result) {
if (result == null) {
Toast.makeText(getActivity(), "There is some wrong,and data can not be displayed", Toast.LENGTH_LONG).show();
return;
}
WeatherForecastDataList = result;
//Display the ListView.
WeatherAdapter adapter = new WeatherAdapter(getActivity(), R.layout.weather_row,WeatherForecastDataList);
listView.setAdapter(adapter);
}
}
}
Here is my logcat.
08-01 19:45:59.857 21260-21260/com.theotziomakas.weatherapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:153)
at com.theotziomakas.weatherapp.Fragments.WeatherAdapter.<init>(WeatherAdapter.java:34)
at com.theotziomakas.weatherapp.Fragments.ForecastFragment$MyTask.onPostExecute(ForecastFragment.java:144)
at com.theotziomakas.weatherapp.Fragments.ForecastFragment$MyTask.onPostExecute(ForecastFragment.java:98)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4867)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
at dalvik.system.NativeStart.main(Native Method)
You need to implement onSaveInstanceState to save the data, then retrieve it in onCreateView
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("YourVariableName", yourVariable);
super.onSaveInstanceState(savedInstanceState);
}
Then in onCreateView
if (savedInstanceState != null) {
yourVariable = savedInstanceState.getString("YourVariableName");
}
Check out the documentation for more info

Categories

Resources