Android App - HttpURLConnection in onCreateView - java

I just started to learn developing android app, and I need to call an URL to get the JSON response.
Here is my java class :-
public class SpeakersFragment extends Fragment {
List<String> titles;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_speakers, container, false);
initData();
RecyclerView rv = (RecyclerView)view.findViewById(R.id.info_speaker_recycler);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
RecyclerAdapter adapter = new RecyclerAdapter(getActivity(), titles);
rv.setAdapter(adapter);
new GetSpeakersList().execute(URL);
return view;
}
public class GetSpeakersList extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
When I checked the logs, the response is not there at all. I tried creating a new project, it works fine if I call the GetSpeakersList in onCreate() instead of onCreateView.
Can guide me how to get this to work? Thanks!

Using an AsyncTask can be quite cumbersome to use for constant Network requests: Try using a popular, well-supported library for networking: Here are two popular ones:
1) Retrofit
OR
2) Volley

this is how i ask for data hope you can use it to your means
urlConnection = new URL("www.example.com");
connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type","application/json;charset=UTF-8");
connection.setReadTimeout(60000);
connection.setConnectTimeout(60000);
connection.connect();
dataOutputStream = new
DataOutputStream(connection.getOutputStream());
Log.d("OUTPUT :",param);
dataOutputStream.writeBytes(param);
dataOutputStream.flush();
dataOutputStream.close();
//incoming data
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new
InputStreamReader(in));
result = new StringBuilder(16384);
String line;
while ((line = reader.readLine()) != null)
{
result.append(line);
}
Log.d("INPUT :",result.toString());

Related

How to pass a post value to server and store the result in the listview android

this is my listview where data is coming from the remote server in the JSON format so everything is working fine but now I have to pass a certain value to the server and then make a filter based on that value and then load only the desired result into the listview
public class Reciepe extends AppCompatActivity {
String Barname;
TextView food,price;
private ListView reciepeListView;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reciepe);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(Color.parseColor("#FFBC03"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
new JSONTask().execute("http://thehostels.in/Foody/reciepe_json.php");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(Reciepe.this)
.defaultDisplayImageOptions(options)
.build();
com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
reciepeListView = (ListView)findViewById(R.id.list_recipe);
Intent intent=getIntent();
if(intent!=null){
Barname=intent.getStringExtra("Type");
Log.e("Type",Barname);
}
if (Barname != null) {
switch (Barname) {
case "Punjabi":
getSupportActionBar().setTitle("Punjabi");
break;
case "Chinese":
getSupportActionBar().setTitle("Chinese");
break;
case "South Indian":
getSupportActionBar().setTitle("South Indian");
break;
case "Gujarati":
getSupportActionBar().setTitle("Gujarati");
break;
case "Chicken":
getSupportActionBar().setTitle("Chicken");
break;
}
}
}
public class JSONTask extends AsyncTask<String, String, List<Listview_reciepe_conveyer>> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Reciepe.this, "loading,please wait...", null, true, true);
}
#Override
protected List<Listview_reciepe_conveyer> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("list");
List<Listview_reciepe_conveyer> fixture_conveyerList = new ArrayList<Listview_reciepe_conveyer>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Listview_reciepe_conveyer fixtureList = new Listview_reciepe_conveyer();
fixtureList.setImage(finalObject.getString("image"));
fixtureList.setFood(finalObject.getString("food"));
fixtureList.setPrice(finalObject.getString("price"));
fixture_conveyerList.add(fixtureList);
}
return fixture_conveyerList;
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<Listview_reciepe_conveyer> result) {
super.onPostExecute(result);
if (result !=null) {
loading.dismiss();
ListAdapter adapter = new ListAdapter(Reciepe.this, R.layout.custom_recipe_list, result);
reciepeListView.setAdapter(adapter);
}
else
{
Toast.makeText(Reciepe.this, "No Internet Connection!", Toast.LENGTH_LONG).show();
loading.dismiss();
}
}
}
public class ListAdapter extends ArrayAdapter {
private List<Listview_reciepe_conveyer> reciepe_conveyerList;
private int resource;
private LayoutInflater inflater;
public ListAdapter(Context context, int resource, List<Listview_reciepe_conveyer> objects) {
super(context, resource, objects);
reciepe_conveyerList = objects;
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
ImageView food_photo;
final TextView food,price;
food_photo = (ImageView)convertView.findViewById(R.id.food_photo);
food = (TextView)convertView.findViewById(R.id.food_name);
price = (TextView)convertView.findViewById(R.id.food_price);
ImageLoader.getInstance().displayImage(reciepe_conveyerList.get(position).getImage(), food_photo);
food.setText(reciepe_conveyerList.get(position).getFood());
String newprice= ("Rs."+reciepe_conveyerList.get(position).getPrice());
price.setText(newprice);
reciepeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i=new Intent(Reciepe.this,Description.class);
i.putExtra("Dish",reciepe_conveyerList.get(position).getFood());
i.putExtra("Price",reciepe_conveyerList.get(position).getPrice());
startActivity(i);
}
}
);
return convertView;
}
}
}
this is what my code looks like where i am loading a list from an api,
so i am using AsyncTask to load the listview but i do not know how to make the post request , i have updated the api it os taking the post values but what changes do i need to make on android level.., i have to pass the 'barname' as the post parameter...
On:
protected List<Listview_reciepe_conveyer> doInBackground(String... params) {
Try:
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("firstParam", "paremeterValue"));
//your param nr.1.
//This is the value that you want to send.
//It is represented like 'name=value', or in your case 'firstParam=parameterValue'.
//You need to edit this field in respect to what you are doing.
params.add(new BasicNameValuePair("secondParam", "your2parameter"));
//your param nr.2
//This is the value that you want to send.
//It is represented like 'name=value', or in your case 'secondParam=your2parameter'.
//You need to edit this field in respect to what you are doing.
params.add(new BasicNameValuePair("thirdParam", "anotherParameter"));
//your param nr.3
//This is the value that you want to send.
//It is represented like 'name=value', or in your case 'thirdParam=anotherParameter'.
//You need to edit this field in respect to what you are doing.
// Write(add) parameters to your request
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
Before your..:
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
...
EDITED
private String getQuery(List<BasicNameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (String pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
This function turn's the List params, in a String with the format, 'name=value' which is needed to send via request.
For more info see Query String.
Please do NOT copy and paste the solution, you also need to understand what you are doing and replace variables/methods accordingly, for this code to work.
Best

Call Async task from start of activity in android

I have a Async task like this in my app:
private class getUserSummary extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DashboardActivity.this);
pDialog.setMessage("Getting sales summary...");
//pDialog.setTitle("Getting sales summary...");
pDialog.setIndeterminate(true);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... strings) {
String JsonResponse = null;
String JsonDATA = "email=my email address";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
ServiceUrl smf = new ServiceUrl();
URL url = new URL(smf.getUserSummaryUrl());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
// json data
writer.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 400) {
InputStream inputResponse = urlConnection.getErrorStream();
reader = new BufferedReader(new InputStreamReader(inputResponse));
StringBuffer errorBuffer = new StringBuffer();
String errorLine;
while ((errorLine = reader.readLine()) != null) {
errorBuffer.append(errorLine + "\n");
}
Log.i("Error text", errorBuffer.toString());
return new JSONObject(errorBuffer.toString());
}
//Log.i("Response code", String.valueOf(inputStream));
InputStream inputStream = urlConnection.getInputStream();
//input stream
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
//response data
Log.i("RESPONSE", JsonResponse);
return new JSONObject(JsonResponse);
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("ERROR", "Error closing stream", e);
}
}
}
return null;
}
protected void onPostExecute(JSONObject result) {
pDialog.dismiss();
//post operation here
}
}
and calling this in onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
ButterKnife.bind(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initCollapsingToolbar();
new getUserSummary().execute();
}
I am running this as soon as user login activity distroyed. that's why I need to call this on onCreate() method. But I am getting this error when the call this in onCreate() method
android.view.WindowLeaked: Activity softlogic.computers.softlogicsalesreward.DashboardActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{5329b90 V.E...... R......D 0,0-1002,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:603)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:109)
at android.app.Dialog.show(Dialog.java:505)
at softlogic.computers.softlogicsalesreward.DashboardActivity$getUserSummary.onPreExecute(DashboardActivity.java:88)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at softlogic.computers.softlogicsalesreward.DashboardActivity.onResume(DashboardActivity.java:65)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
at android.app.Activity.performResume(Activity.java:7015)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4210)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
is there any other event where I can call this? or what I am doing wrong?
Your asyncTask must be like this.After see your code it may possible that You may forgot some method of AsyncTask.Compare with this example to better understand.
This is complete example of asyncTask:
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
#Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
call like this:
new AsyncTaskRunner (this).execute();
you can use thread policy for this. It's work great.
Just add two line below setcontent.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
You Forget to call pDialog.dismiss();
in onPostExecute method of Async task

Fetching Data from JSON using AsyncTask

I have created a fragment which if it is activated it will show MySQL data but it takes time to fetch the data and show it on a custom ListView.
I tried to implement AsyncTask so that while fetching the data you can do something else on the fragment while waiting but am having this error.
"FATAL EXCEPTION: main java.lang.NullPointerException"
Here is the code
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_markets,container,false);
//lvMarkets.setAdapter(new CustomAdapter(getActivity().getApplicationContext(),Symbols,Prices,Balances));
DBHelper db = new DBHelper(getActivity().getApplicationContext());
final ListView lvMarkets = (ListView)getActivity().findViewById(R.id.lvMarkets);
final String c_androidid = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
final Cursor rs = db.getID(c_androidid);
rs.moveToFirst();
final String c_login = rs.getString(rs.getColumnIndex(DBHelper.c_login));
AsyncTaskRunner taskRunner = new AsyncTaskRunner();
taskRunner.execute(c_login);
lvMarkets.setAdapter(jAdapter);
return rootView;
}
private class AsyncTaskRunner extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params)
{
final String fin_login=params[0];
StringRequest stringRequest = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
Log.d(debug,response);
try
{
jsonArray =new JSONArray(response);
jAdapter= new JsonAdapter(getActivity(),jsonArray,login);
}
catch (JSONException e)
{
Log.d(debug,e.toString());
}
}
}, new Response.ErrorListener()
{
public void onErrorResponse(VolleyError error)
{
Log.d(debug,error.toString());
}
}){
#Override
protected Map<String,String>getParams()
{
Map<String,String> params=new HashMap<String,String>();
params.put("c_login",fin_login);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(stringRequest);
return fin_login;
}
}
Hope someone could point out what went wrong with my code and someone could also point out on how to fetch data on online much more faster.
Thanks...
Try this:
private void parsingValues() {
URL obj = null;
HttpURLConnection con = null;
String USER_AGENT = "Mozilla/5.0";
try {
//parameter to post
String POST_PARAMS = "deviceos=" + deveiceOs + "&devicetype=" + deviceType +"&deviceid=" ;
obj = new URL("Your URI");
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//getResponse
String subsResponse = response.toString();
final JSONObject responsesubs = new JSONObject(subsResponse);
//Here your parsing process
}
}
});
} else {
System.out.println("POST request not worked");
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Call this method to your doinbackground of Asynhronous Task(parsingValues())

Android app can not connect to localhost server

I've created Database in my localhost, and want parse data from it with android app.I Create server with NodeJS and it works i can see the Database in browser, but my android app can't connect with this localhost server.
Here is my Java code.
public class MainActivity extends AppCompatActivity {
protected TextView tvData;
public static ArrayList<String> titleList = new ArrayList<String>();
private static ArrayAdapter<String> adapter;
private static ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView)findViewById(R.id.tvJsonItem);
// adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.listView1, titleList);
// lv = (ListView) findViewById(R.id.listView1);
new JSONTask().execute("http://10.0.2.2:3000/api/people");
}
public class JSONTask extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
int statusCode = 0;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
connection.connect(); //connect to server
statusCode = connection.getResponseCode();
if (statusCode == 200) {
System.out.println("Server responded with code: " + statusCode);
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("people");
StringBuffer finalBufferdData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObj = parentArray.getJSONObject(i);
String peopleName = finalObj.getString("name");
Integer age = finalObj.getInt("age");
finalBufferdData.append(peopleName + "-->" + age + "\n");
Log.i("Hakob_log",peopleName + "-->" + age + "\n");
}
return finalBufferdData.toString(); //pases result to POstExecute
}else{
Log.i("Hakob_log","Error");
}
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}catch(JSONException e){
e.printStackTrace();
}
finally {
if(connection !=null) {
connection.disconnect();
}
try {
if(reader !=null) {
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
}
}
}
I thnk something wrong with this line
new JSONTask().execute("http://localhost:3000/api/people");
Thanks
Use the IP-address of the computer that you are referring to as localhost instead, this should solve your problem e.g.:
new JSONTask().execute("http://10.0.0.100:3000/api/people");

How to start an Activity from AsyncTask?

I've build an AsyncTask and want to start another Activity when it ends (onPostExecute) but it won't work and I can't find the problem. Maybe there is a problem with String, String, String ?
Here is my code:
public class StartSearch extends AsyncTask<String, String, String> {
private Activity activity;
#Override
protected String doInBackground(String... strings) {
StringBuilder sb = new StringBuilder();
String http = "https://list-creater-service.herokuapp.com/api/v1/search";
HttpURLConnection urlConnection = null;
JSONObject json = null;
HttpResponse response = null;
try {
//connect to server
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Host", "list-creater-service.herokuapp.com");
urlConnection.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("gamemode", gametype);
jsonParam.put("country", selCountry);
jsonParam.put("min_size", minSize);
jsonParam.put("max_size", maxSize);
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
int HttpResult = urlConnection.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(),"utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String jsonS = sb.toString();
JSONArray jsonArray = new JSONArray(jsonS);
int length = jsonArray.length();
String[] names = new String[length];
for (int i = 0; i < length; i++) {
JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
ArrayList serverList = new ArrayList();
serverList.add(jsonObject.getString("name"));
serverData = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = serverData.edit();
Set<String> set = new HashSet<String>();
set.addAll(serverList);
editor.putStringSet("name", set);
editor.commit();
System.out.println(jsonObject.getString("name"));
names[i] = jsonObject.getString("name");
}
//String name = jsonObject.getString("name");
System.out.println("" + sb.toString());
}else{
System.out.println(urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(urlConnection!=null)
urlConnection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
activity.startActivity(new Intent(activity, ServerIndex.class));
}
}
Need some help!
Thx :)
You have Activity activity declared , but you have not assigned your current activity context to it . Assign the current activity context to it.
Like
activity=currentContext;
You should use runOnUIThread in your onPostExecute
runOnUiThread(new Runnable() {
public void run() {
activity.startActivity(new Intent(activity, ServerIndex.class));
}});
And as Raghunandan said, activity is not initialized. You can access the startActivity method from your StartSearch class by using
SomeActivity.this.startActivity (SomeActivity has to be initialized)
And since onPostExecute runs on the UI thread, you may or may not call runOnUIThread.

Categories