Click here to Skip to main content
14,974,887 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a project in which i read data from SQL Server. In an Activity i try to read data from two DB and then filter one of them from the other and after all all display in ListView,it has done in onCreate method, but it takes some time,However its OK. Now i want to set an Update Button and exactly Call the same methods as in onCreate is. Well, cause of Processing time, i want to display a ProgressBar or ProgressDialog to the End-user. I know i should put my methods in Thread, and googled alot, but non of them worked. The ProgressBar disappear after all methods. This is my Last try that gives me java.lang.RuntimeException cause of calling Constructor i think,because it point to constructor in logCat : Here is what i have done in update Button. And This Class name is IceCream that i instance it here with the Constructor.
Java
update.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick (View v){

                   progressBar.setVisibility(View.VISIBLE);
                   blackListPartCodes.clear();
                   typeArray.clear();
                   typeAdapter.clear();
                   handler = new Handler() {
                       @Override
                       public void handleMessage(Message msg)
                       {
                           progressBar.setVisibility(View.GONE);
                           super.handleMessage(msg);
                       }

                   };
                   progressBar.setVisibility(View.VISIBLE);
                   ConnectionHelper blackListConnection = new ConnectionHelper();
                   CallableStatement callableStatement;
                   try {
                       callableStatement = blackListConnection.getConnection().prepareCall("{call SpGetAllIceBlackListProduct}");
                       callableStatement.execute();
                       ResultSet resultSet = callableStatement.getResultSet();
                       if(resultSet.next()) {
                           do {
                               String partCode = new String(resultSet.getString("PartCode"));
                               blackListPartCodes.add(partCode);
                           }while (resultSet.next());
                       }
                       blackListConnection.closeConnection();
                       resultSet.close();
                       callableStatement.close();
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }catch (Exception e) {
                       Toast.makeText(getApplicationContext(), "Try Again",Toast.LENGTH_SHORT).show();
                   }
                   new Thread() {
                       public void run() {

                           Statement statement = null;
                           String query;
                           query = "MyQuery";
                           try {
                               ConnectionHelper connectionHelper2 = new ConnectionHelper();
                               statement = connectionHelper2.getConnection().createStatement();

                                   ResultSet resultSet = statement.executeQuery(query);

                               if(resultSet.next()) {
                                   do {
                                       setPartName(resultSet.getString("XX"));
                                       setPartCode(resultSet.getString("XX"));
                                       setPrice(resultSet.getString("XX"));
                                       setUnitName(resultSet.getString("XX"));


                                       IceCream iceCream = new IceCream(getPartName(), getPartCode(), getUnitName(), getPrice());
                                       iceCreams.add(iceCream); //This gives java.lang.RuntimeException: Can't create handler inside thread in Logcat,


                                   } while (resultSet.next());
                               }
                               connectionHelper2.closeConnection();
                               statement.close();
                               resultSet.close();
                           }
                           catch (SQLException e) {

                          }catch (Exception e) {
                              Toast.makeText(getApplicationContext(), "Try Again",Toast.LENGTH_SHORT).show();

                           }
                           handler.sendEmptyMessage(0);
                       }

                   }.start();

                   checkMatches(iceCreams, blackListPartCodes);
                   for(int i = 0; i<iceCreams.size(); i++) {
                       typeArray.add(iceCreams.get(i).getPartName());
                       typeAdapter.getItemViewType(R.id.listView);
                       iceCreamTypeList.setAdapter(typeAdapter);
                   }

           }
           }
           );



First, it gives me java.lang.RuntimeException: Can't create handler inside thread in the second Connection(Connection2) and the Line `

Java
catch (Exception e) {
       Toast.makeText(getApplicationContext(), "Try Again",Toast.LENGTH_SHORT).show();
                            }


And after i removed it, it gives me error in Constructor of IceCreame. This Line :
Java
IceCream iceCream = new IceCream(getPartName(), getPartCode(), getUnitName(), getPrice());


Note that this class name is IceCream. Any help will Appreciate. I Googled alot, but to chance, where i am doing wrong?</b>

What I have tried:

I have tried java.os.Handle also, but no chance.
Any Solution?
Posted
Updated 25-May-16 21:23pm
v2
Comments
Mike Barthold 26-May-16 3:32am
   
Beside my approach of using an Asyntask below, I'd like to add that you are maybe just missing a .runOnUIThread call?
Looks to me as you have messed up some things in threading. What does the constructor of IceCream do? any UI/Handler/Message related stuff that needs to run in the UI thread?
Instanciate it in UI thread.
I hope I got it right :)

1 solution

Have you tried to simply use an AsyncTask? It is made for situations like these...

Java
AsyncTask<void,> asyncTask = new AsyncTask<void,>() {
			AlertDialog dialogWindow;
			@Override
			protected void onPreExecute() {
                // Show a dialog to the user
				AlertDialog.Builder dialog = new AlertDialog.Builder(context);
				LayoutInflater inflater = context.getLayoutInflater();
                // Find this simple layout attached below this code block
				final View view = inflater.inflate(R.layout.simple_progress_dialog, null);
				((TextView)view.findViewById(R.id.simple_progresstext)).setText(displayText);
				dialog.setView(view);
				dialogWindow = dialog.create();
				dialogWindow.show();
			}

			@Override
			protected Void doInBackground(Void... params) {
				try {
                    // Execute your job...

				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				if (dialogWindow != null) {
					dialogWindow.dismiss();
					dialogWindow = null;
				}
                // Continue with your program...
                // This method is already back in UI thread!

			}
		};

        // this line starts your background work
		asyncTask.execute();


Inflate a simple layout like this to show to the user
(place it in the layout folder):

<linearlayout>
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <progressbar>
        android:id="@+id/simple_progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:progressDrawable="@drawable/simple_progress_circular"
        android:visibility="visible"
        />

    <textview>
        android:id="@+id/simple_progresstext"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:textAppearance="@android:style/TextAppearance.Small"
        android:text="Working..."/>

</textview></progressbar></linearlayout>


This layout uses a circular progress (place it in the drawable folder):

<rotate xmlns:android="http://schemas.android.com/apk/res/android">
        android:fromDegrees="90"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="360">

    <shape>
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="7.0">
        <gradient>
            android:startColor="@android:color/holo_blue_bright"
            android:centerColor="@android:color/holo_blue_light"
            android:endColor="@android:color/holo_blue_dark"
            android:angle="0"
            android:type="sweep"
            android:useLevel="false" />
    </gradient></shape>

</rotate>
   
Comments
Mike Barthold 26-May-16 3:28am
   
Sorry, answering questions with xml content messed my answer up... the two xml files are corrupted.

in the first xml block (the progress dialog), this code is missing:


<ProgressBar
android:id="@+id/simple_progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progressDrawable="@drawable/simple_progress_circular"
android:visibility="visible"
/>

<textview android:id="@+id/simple_progresstext" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:textcolor="@android:color/black" android:textappearance="@android:style/TextAppearance.Small" android:text="Working...">
</LinearLayout>

in the second block, only the closing tag is missing

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900