0

Before trying to get a row of data from a MySQL server, I used a column and managed to get that into a listView through tutorials. But for getting data in a row from a table, I couldn't manage to put it into a listView.

So what I'm trying to do is put "shift" from background worker into a listview.

PHP SQL query:

$sql = "SELECT id, employee, hours FROM selected_shifts WHERE day = '$day';";

Navigation drawer from Main Activity:

if (items[0].equals(mExpandableListTitle.get(groupPosition))) {
                if (items[0].equals(mExpandableListTitle.get(childPosition))) {
                    String day = "Monday";
                    OnChoice(day);
                } else if (items[1].equals(mExpandableListTitle.get(childPosition))) {
                    String day= "Tuesday";
                    OnChoice(day);
                } else if (items[2].equals(mExpandableListTitle.get(childPosition))) {
                    String day = "Wednesday";
                    OnChoice(day);
                } else if (items[3].equals(mExpandableListTitle.get(childPosition))) {
                    String day = "Thursday";
                    OnChoice(day);
                } else if (items[4].equals(mExpandableListTitle.get(childPosition))) {
                    String day = "Friday";
                    OnChoice(day);
                }
            }

            mDrawerLayout.closeDrawer(GravityCompat.START);
            return false;
        }
    });
}

public void OnChoice(String day) {
    String type = "choice";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, day);
}

Background worker(getting data from MySQL server):

public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
    context = ctx;
}
@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String shifts_url = "***PHP LINK***";
    if(type.equals("choice")) {
        try {
            String day = params[1];
            URL url = new URL(shifts_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("day","UTF-8")+"="+URLEncoder.encode(day,"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 shift="";
            String line="";
            while((line = bufferedReader.readLine())!= null) {
                shift += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return shift;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Status");
}

@Override
protected void onPostExecute(String shift) {
    //Toast the data as json
    Toast.makeText(context, shift, Toast.LENGTH_LONG).show();
}

@Override
protected void onProgressUpdate(Void... values)
{
    super.onProgressUpdate(values);


   }
}

EDIT

Putting it into ListView:

public void onTaskCompleted(String shift) {
    try {
        loadIntoListView(shift);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

private void loadIntoListView(String shift) throws JSONException {
    JSONArray jsonArray = new JSONArray(shift);
    String[] list = new String[jsonArray.length()];
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject obj = jsonArray.getJSONObject(i);
        list[i] = obj.getString(shift);
    }
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
    listView.setAdapter(arrayAdapter);
}
  • What is the issue here? are you getting something in `onPostExecute()` ? if so then you just need to pass the data back to your main and show it. – Mohamed Hamdaoui Oct 17 '17 at 21:01
  • The toast works to show "shift" as a json in the onPostExecute() , but I was struggling to be able to get it back into the MainActivity and put it into a ListView. –  Oct 17 '17 at 21:03
  • I will write an answer for that in 2 min – Mohamed Hamdaoui Oct 17 '17 at 21:04

2 Answers2

0

At your onPostExecute() you should add the "shift" to a dataSet in your adapter.

codeFreak
  • 353
  • 1
  • 3
  • 15
0

So what you want to do to pass the shift back is use a custom "Listener".

Create this

public interface TaskListener {
    void onTaskCompleted(String shift);
}

And on your BackgroundWorker change the constructor as follow:

TaskListener taskListener;
BackgroundWorker(Context context, TaskListener taskListener){
  this.context = context;
  this.taskListener = taskListener;
}

Then on the onPostExecute method, do a taskListener.onTaskCompleted(shift).

When you call the BackgroundWorker constructor pass this as the second parameter:

BackgroundWorker backgroundWorker = new BackgroundWorker(this, this)

Then implement TaskListener on your Main and implement the method. Something like this:

... MainActivity implements TaskListener
...
@override
onTaskCompleted(String shift) {
// You have your `shift` here to do with as you please
}
  • In the MainActivity I'm getting a few errors; the first is with BackgroundWorker backgroundWorker = new BackgroundWorker(this, this); where it's saying "(Context, james.MyApplication.BackgroundWorker.TaskListener) in BackgroundWorker cannot be applied to (MainActivity, james.MyApplication.MainActivity)" and the second for onTaskCompleted it's saying "Invalid method declaration; return type required" –  Oct 17 '17 at 21:27
  • What about passing the listView it self with the `BackgroundWorker(..)` and use it there ? –  Oct 17 '17 at 21:47
  • Please could you explain a little more on how this would be done –  Oct 17 '17 at 21:54
  • My method will work, just follow it through, The first error you are getting is because you didn't change the constructor of the `BackgroundWorker` as I said, look at my response above. The second error I am not sure what you wrote to get that. – Mohamed Hamdaoui Oct 18 '17 at 03:00
  • I've looked at it and got it working, thanks! However, my initial problem of putting it into a ListView isn't working. I've put the code in the original post. –  Oct 18 '17 at 09:29
  • If the initial issue works, then mark this as the correct answer. As far as the new issue, that's because you are doing this: `list[i] = obj.getString(shift);` As far as I understand, your `obj` is the JsonObject item of the list, and you want to get what exactly from it? it should be something like `list[i] = obj.getString("name_of_the_attribute_in_the_Json");` It would help if I see the json of course and how you want to parse. – Mohamed Hamdaoui Oct 18 '17 at 13:57
  • The original question in the post is about parsing a row of data into a ListView, here's the json: [{"id":0"day":"employee":"James","hours":"10:30-18:00"}] and in the ListView I've tried to get it so Id, employee and hours are all on separate lines. Thanks for your help :) –  Oct 18 '17 at 15:25
  • Well if you do `list[i] = obj.getString("employee");` you will show a list of the names of the employees. Make sure that works first. Then if you want to show each information on a different line, you have to create a custom Adapter. Like this: https://stackoverflow.com/questions/8166497/custom-adapter-for-list-view – Mohamed Hamdaoui Oct 18 '17 at 15:30