I am trying to get a list of data from MySQL that is hosted then return the result in a listview. But I am not able to make it when using fragments.
I am getting the following error:
com.example.test.myapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.exampletest.myapp, PID: 31491
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at com.example.test.myapp.homeOperation.doInBackground(homeOperation.java:71)
at com.example.test.myapp.homeOperation.doInBackground(homeOperation.java:23)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
With the class shown below: I connect to the server, then I fetch the result, so I can parse the data and put in in ArrayLists.
public class homeOperation extends AsyncTask<String, Void, String> {
List<String> title_list = new ArrayList<String>();
List<String> id_list = new ArrayList<String>();
Context context;
AlertDialog alertDialog;
homeOperation(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://xxxx/data.php";
if (type.equals("home")) {
try {
String events = params[1];
String task_owner = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("events", "UTF-8") + "=" + URLEncoder.encode(events, "UTF-8") + "&"
+ URLEncoder.encode("task_owner", "UTF-8") + "=" + URLEncoder.encode(task_owner, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
String[] arr = result.split("--");
for (int i = 0; i < arr.length; i++) {
String cur = arr[i];
title_list.add(cur.split(":")[0]);
id_list.add(cur.split(":")[1]);
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
Toast toast = Toast.makeText(this.context, result, Toast.LENGTH_LONG);
toast.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Now, this is the class in which I'm trying to get the data from the homeOperation class and then put the data into a ListView.
public class ContentFragment extends Fragment {
ListView lv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_fragment, container, false);
lv = (ListView) view.findViewById(R.id.resultList);
String type = "home";
homeOperation homeOperation = new homeOperation(ContentFragment.this.getActivity());
homeOperation.execute(type, "", "");
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(ContentFragment.this.getActivity(), android.R.layout.simple_list_item_1, homeOperation.title_list);
lv.setAdapter(arrayAdapter);
//addButton onClick
ImageButton addButton = (ImageButton) view.findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addPaige(view);
}
});
return view;
}
public void addPaige(View v) {
Intent goToAddPaige = new Intent(getActivity(), AddPaige.class);
startActivity(goToAddPaige);
}
}
I think there is a problem when sending the context using fragments.
title_list will have no data because your AsyncTask.execute() will be done after lv.setAdapter(arrayAdapter);.
So if you want to handling title_list with enough data, use android.os.Handler in onPostExecute() to send your result of AsyncTask.
Try as below:
Your AsyncTask
public class homeOperation extends AsyncTask<String,Void,String> {
List<String> title_list = new ArrayList<String>();
List<String> id_list = new ArrayList<String>();
Context context;
Handler handler;
AlertDialog alertDialog;
homeOperation(Context ctx, Handler hnd) {
context = ctx;
handler = hnd;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://xxxx/data.php";
if (type.equals("home")) {
try {
String events = params[1];
String task_owner = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("events", "UTF-8") + "=" + URLEncoder.encode(events, "UTF-8") + "&"
+ URLEncoder.encode("task_owner", "UTF-8") + "=" + URLEncoder.encode(task_owner, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
String[] arr = result.split("--");
for (int i = 0; i < arr.length; i++) {
String cur = arr[i];
title_list.add(cur.split(":")[0]);
id_list.add(cur.split(":")[1]);
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
Toast toast = Toast.makeText(this.context, result, Toast.LENGTH_LONG);
toast.show();
handler.sendEmptyMessage(0);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Your Fragment
public class ContentFragment extends Fragment {
ListView lv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.content_fragment,container,false);
lv = (ListView) view.findViewById(R.id.resultList);
ViewHandler viewHnd = new ViewHandler(ContentFragment.this); // add this handler for parameter of yout AsyncTask.
String type = "home";
homeOperation homeOperation = new homeOperation(ContentFragment.this.getActivity(), viewHnd);
homeOperation.execute(type, "", "");
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(ContentFragment.this.getActivity() , android.R.layout.simple_list_item_1, homeOperation.title_list);
//
// lv.setAdapter(arrayAdapter);
//addButton onClick
ImageButton addButton = (ImageButton) view.findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addPaige(view);
}
});
return view;
}
public void addPaige(View v){
Intent goToAddPaige = new Intent(getActivity(), AddPaige.class);
startActivity(goToAddPaige);
}
private static class ViewHandler extends Handler {
private final WeakReference<ContentFragment> mFragment;
ViewHandler(ContentFragment fragment) {
mFragment = new WeakReference<ContentFragment>(fragment);
}
#Override
public void handleMessage(Message msg) {
ContentFragment fragment = mFragment.get();
if (fragment != null) {
fragment.handleMessage(msg);
}
}
}
private void handleMessage(Message msg) {
if (msg.what == 0) {
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(ContentFragment.this.getActivity() , android.R.layout.simple_list_item_1, homeOperation.title_list);
lv.setAdapter(arrayAdapter);
}
}
}
Replace:
for (int i = 0; i < arr.length; i++) {
String cur = arr[i];
title_list.add(cur.split(":")[0]);
id_list.add(cur.split(":")[1]);
}
with:
for (int i = 0; i < arr.length; i++) {
String cur = arr[i];
String[] temp = cur.split(":");
if (temp.length == 2){
title_list.add(cur.split(":")[0]);
id_list.add(cur.split(":")[1]);
}
}
The stack trace is very clear by itself:
java.lang.Thread.run(Thread.java:818) Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 at
which should translate to this line:
id_list.add(cur.split(":")[1]);
You shouldn't expect that the split method will always give you a certain number of substrings. So you have to write a fallback for when it doesn't.
Related
I have a login form which verifies whether the username or password matches the ones in my database but i coded the verification in another java class which looks like this:
AlertDialog dialog;
Context context;
public background (Context context){
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
#Override
protected String doInBackground(String... voids) {
String result = "";
String user = voids[0];
String pass = voids[1];
String connStr = "http://xzylrey1.heliohost.org/loginandroid.php";
try {
URL url = new URL(connStr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream ops = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ops, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(user, "UTF-8")
+ "&&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(pass, "UTF-8");
writer.write(data);
writer.flush();
writer.close();
ops.close();
InputStream ips = http .getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "ISO-8859-1"));
String line = "";
while((line = reader.readLine()) != null){
result += line;
}
reader.close();
ips.close();
http.disconnect();
return result;
} catch (MalformedURLException e) {
result = e.getMessage();
} catch (IOException e) {
result = e.getMessage();
}
return result;
This is the main class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_Password);
btnLogin = findViewById(R.id.btn_Login);
}
public void moveToActivityTwo(){
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
public void loginBtn(View view) {
String user = et_username.getText().toString();
String pass = etPassword.getText().toString();
background bg = new background(this);
bg.execute(user, pass);
moveToActivityTwo();
I tried putting the method below the bg.execute line, but then it would just automatically redirect to the other activity is there another way to do this?
You need to move the moveToActivityTwo() method to the end of the onPostExecute() method.
It will look like this:
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
context.moveToActivityTwo();
}
It calls callback pattern.
My problems :
1. I have error on it.
2. Why cannot go to the next page when I use startActivity?
3. How to solve?
4. I already use startActivity by using Intent method
Below is prove 1 :
Below is prove 2 :
Below is prove 3 :
Below is code snippet :
public void OnLog(View view)
{
String Username = username.getText().toString();
String Password = password.getText().toString();
String type = "login";
if(Username.equals("") || Password.equals(""))
{
Toast.makeText(getApplicationContext(), "Please fill the Username and Password!", Toast.LENGTH_LONG).show();
}
else {
Background bg = new Background(Context, act);
bg.execute(type, Username, Password);
}
}
Below is coding for Background.java :
public class Background extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
Background(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String type = params[0];
String login_url = "http://172.20.10.4/LoginLab3.php";
String reg_url = "http://172.20.10.4/RegisterLab3.php";
if (type.equals("login")) {
try {
String username = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "ISO-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else if(type.equals("register"))
{
try {
String name = params[1];
String surname = params[2];
String age = params[3];
String username = params[4];
String password = params[5];
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
+URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
+URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null)
{
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute()
{
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result)
{
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Login Status");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Login.this, Welcome.class));
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
dialog.create().show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
Help me! i have some problem on it. I already use almost all method, but cannot go to the next page. Why ?
Activity OnCreate Code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Pass activity to Async Task
new Background(this).execute();
}
Async Task
public class Background extends AsyncTask<Void,Void,Void> {
private Context context;
public Background(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent(context, TargetActivity.class);
context.startActivity(intent);
((Activity)context).finish();
}
}
Try context.startActivity() because AsyncTask class don't have startActivity() method inherited.
Also, pass the activity in the constructor and assign it to a variable and use that variable while creating intent
Context context;
Activity activity;
AlertDialog alertDialog;
Background(Context ctx, Activity act) {
context = ctx;
activity = act;
}
inside onClick()
context.startActivity(new Intent(activity, Welcome.class));
I'm reading some text from HttpUrlConnection request and putting it in ArrayList every iteration of a loop.
All works perfect, except items in ListView don't updating in UI after every iteration of a loop (only at the end).
I'm tried next 4 methods: arrayAdapter.notifyDataSetChanged(), listView.invalidateViews(), runOnUiThread(), onPostExecute() nothing helps.
Here is my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<String> news = new ArrayList<>();
ArrayList<String> headers = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
static JSONArray array;
NewsUnpacker unpacker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
String link = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
NewsLoader newsLoader = new NewsLoader();
array = null;
try {
array = newsLoader.execute(link).get();
} catch (Exception e) {
e.printStackTrace();
}
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, headers);
listView.setAdapter(arrayAdapter);
final int size = 15;
for (int i = 0; i < size; i++) {
try {
unpacker = new NewsUnpacker(this);
String info = unpacker.execute("https://hacker-news.firebaseio.com/v0/item/" + array.get(i) + ".json?print=pretty").get();
if (info == null) {
unpacker.cancel(true);
return;
}
news.add(info);
headers.add(info.split(System.lineSeparator())[0]);
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
unpacker.cancel(true);
} catch (Exception e) {
e.printStackTrace();
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
static class NewsUnpacker extends AsyncTask<String, Void, String> {
MainActivity activity;
NewsUnpacker(MainActivity activity) {
this.activity = activity;
}
#Override
protected String doInBackground(String... urls) {
String info = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
String title, urlParam;
JSONObject object = new JSONObject(builder.toString());
title = object.get("title").toString();
urlParam = object.get("url").toString();
info = title + System.lineSeparator() + urlParam;
System.out.println(info);
} catch (Exception e) {
e.printStackTrace();
}
return info;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
static class NewsLoader extends AsyncTask<String, Void, JSONArray> {
JSONArray array = null;
#Override
protected JSONArray doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
int data;
while ((data = reader.read()) != -1)
builder.append((char) data);
array = new JSONArray(builder.toString());
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
}
}
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
I'm new to Android and I was trying to communicate with my localhost using php script and accessing a simple database.
I have defined a task in the doInBackground() method which takes a value from the database stored on the localhost(I don't know if that part will work).
I want to set the text in the textview of an activity using the result that the doInBackground Method returns.
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
BackgroundWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String group = params[0];
String child = params[1];
String address = "http://10.0.2.2/conn.php";
URL url = null;
try {
url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("group", "UTF-8") + "=" + URLEncoder.encode(group, "UTF-8") + "&"
+ URLEncoder.encode("child", "UTF-8") + "=" + URLEncoder.encode(child, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
And the Activity class:
public class viewTT extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_tt);
Button btnNextScreen = (Button) findViewById(R.id.button);
TextView txtName = (TextView) findViewById(R.id.textView);
TextView txtName2 = (TextView) findViewById(R.id.textView2);
Intent i = getIntent();
// Receiving the Data
String group= i.getStringExtra("group");
String child = i.getStringExtra("child");
txtName.setText(group+" "+child);
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(group,child);
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), MainActivity.class);
startActivity(nextScreen);
}
});
}
}
I want to set txtName2.
You can use a interface to return data to your activity
Interface
public interface AsyncResponse {
public void onFinish(Object output);
}
SomeAsyncTask Class
public class SomeAsyncTask extends AsyncTask<String, String, String> {
private AsyncResponse asyncResponse;
public SomeAsyncTask(AsyncResponse asyncResponse) {
this.asyncResponse = asyncResponse;
}
#Override
protected String doInBackground(String... params) {
//Do something
.....
//Finally return something
return "returnSomeString";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
asyncResponse.onFinish(s);
}}
In your activity where you want to set view call the SomeAsyncTask class like this
SomeAsyncTask someAsyncTask=new SomeAsyncTask(new AsyncResponse() {
#Override
public void onFinish(Object output) {
String result= (String) output;
//Finally set your views
}
});
someAsyncTask.execute();
}
Define an interface to take result of backgroundworker and make workers constructor to take second parameter that interface.call that interface object on post execute and put your result as parameter. than use it like:
BackgroundWorker backgroundWorker = new BackgroundWorker(this, new bgWorkerListener() {
#Override
public void onResult(String s) {
txtname2.settext(s);
}
});
backgroundWorker.execute(group, child);
Here is your string in main Thread
protected void onPostExecute(String s) {
// s is your string
super.onPostExecute(s);
}
in your BackgroundWorker class add this code...
private String textFortxtName2;
public String getTextFortxtName2() {
return textFortxtName2;
}
public void setTextFortxtName2(String textFortxtName2) {
this.textFortxtName2 = textFortxtName2;
}
then add this
protected void onPostExecute(String s) {
// s is your string
textFortxtName2 = s;
super.onPostExecute(s);
}
now you can get the text frome yor main activity,,,
...
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(group,child);
txtName2.setText(backgroundWorker.getTextFortxtName2());
that's all :)
if there will be any questions or bags please coment