اذهب إلى المحتوى

احمد صوالحة

الأعضاء
  • المساهمات

    29
  • تاريخ الانضمام

  • تاريخ آخر زيارة

أجوبة بواسطة احمد صوالحة

  1. يظهر لي الخطأ التالي عند تشغيل برنامج جافا:

     Java Runtime (class file version 53.0), this version of the Java Runtime only recognizes class file versions up to 52.0

    مع انني استخدم احدث اصدار للـJDK ولدي القيمة JAVA_HOME : C:\Program Files\Java\jdk-15.0.2  في Environment Variables.

    ما هو الـclass file version وكيف أحل هذه المشكلة ؟

    • أعجبني 1
  2. سبب المشكلة هو السطر التالي في كود الـfragment:

    recyclerView = container.findViewById(R.id.recycleViewHome);

    لحل المشكلة يجب تعديل السطر ليصبح هكذا:

    recyclerView = view.findViewById(R.id.recycleViewHome);

    أي أننا إستخدما view بدلاً من container لجلب الـrecyclerView الخاص بنا.

  3. يحدث لدي الخطأ التالي:

    ERROR Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager) ' on a null object reference at com.example.application.Fragments.Home.HomeFragment.onCreate(HomeFragment.java:32)

    الشاشة الرئيسية:

    class MainActivity extends AppCompatActivity {
        private BottomNavigationView bottomNavigationView;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            bottomNavigationView = findViewById(R.id.bottonNavigationView);
            loadFragment(new HomeFragment());
            setBottomNavigationView();
        }
        private void loadFragment(Fragment fragment) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.idMainFrameLayout, fragment);
            fragmentTransaction.commit();
        }
        @SuppressLint("NonConstantResourceId")
        public void setBottomNavigationView() {
            bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
                switch (item.getItemId()) {
                    case R.id.btnSearch:
                        loadFragment(new SearchFragment());
                        break;
                    case R.id.btnFeed:
                        loadFragment(new FeedFragment());
                        break;
                    case R.id.btnShedule:
                        loadFragment(new SheduleFragment());
                        break;
                    case R.id.btnProfile:
                        loadFragment(new ProfileFragment());
                        break;
                    default:
                        loadFragment(new HomeFragment());
                }
                return true;
            });
        }
    }

    كود الfragment:

    class HomeFragment extends Fragment {
        private RecyclerView recyclerView;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_home, container, false);
            recyclerView = container.findViewById(R.id.recycleViewHome);
            recyclerView.setAdapter(new MyAdapter(getMyList()));
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            return view;
        }
        private ArrayList<Store> getMyList() {
            String mTitle = "Google", mSubTitle = "Description";
            int imageView = R.drawable.ic_google_svg;
            ArrayList<Store> storeArrayList = new ArrayList<>();
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
            return storeArrayList;
        }
    }

    واجهة الfragment:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        tools:context=".Fragments.Home.HomeFragment">
        <androidx.recyclerview.widget.RecyclerView
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            android:id="@+id/recycleViewHome"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginStart="20dp"
            android:layout_marginTop="10dp"
            android:layout_marginEnd="20dp"
            android:orientation="vertical"
            tools:listitem="@layout/card_layout_stores" />
    </LinearLayout>

     

  4. احاول جلب بيانات من الـfirebase لكن يظهر لدي الخطأ التالي:

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.luvtas.campingau, PID: 11763
        com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.luvtas.campingau.Model.CamperSiteModel
            at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
            at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
            at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
            at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
            at com.luvtas.campingau.Fragment.ExploreFragment$3.onDataChange(ExploreFragment.java:128)
            at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
            at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
            at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
            at android.os.Handler.handleCallback(Handler.java:790)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:164)
            at android.app.ActivityThread.main(ActivityThread.java:6494)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

    هذا هو الكود:

    private RecyclerView recyclerView;
        private CamperSiteAdapter camperSiteAdapter;
        private List<CamperSiteModel> camperSiteModel;
        EditText seatch_bar;
    private void readCampSite(){
            DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Cte");
            reference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(seatch_bar.getText().toString().equals("")){
                        camperSiteModel.clear();
                        for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                            CamperSiteModel camperSiteModel1 = snapshot.getValue(CamperSiteModel.class);
                            camperSiteModel.add(camperSiteModel1);
                        }
                        camperSiteAdapter.notifyDataSetChanged();
                    }
                }
                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                }
            });
        }

    كود الـmodel:

     public CamperSiteModel() {
        }
        public CamperSiteModel(String camperSiteID, String camperSiteName, String camperSiteImage, String camperSiteType, String camperSiteDistance, String camperSiteInfo, String camperSiteSummary, String camperSiteAddress, String camperSiteLatitude, String camperSiteLongitude, String camperSitePrice1, String camperSitePrice2, String camperSiteEmail, String camperSiteSub) {
            CamperSiteID = camperSiteID;
            CamperSiteName = camperSiteName;
            CamperSiteImage = camperSiteImage;
            CamperSiteType = camperSiteType;
            CamperSiteDistance = camperSiteDistance;
            CamperSiteInfo = camperSiteInfo;
            CamperSiteSummary = camperSiteSummary;
            CamperSiteAddress = camperSiteAddress;
            CamperSiteLatitude = camperSiteLatitude;
            CamperSiteLongitude = camperSiteLongitude;
            CamperSitePrice1 = camperSitePrice1;
            CamperSitePrice2 = camperSitePrice2;
            CamperSiteEmail = camperSiteEmail;
            CamperSiteSub = camperSiteSub;
        }

    فما هي المشكلة ؟

    • أعجبني 1
  5. لدي تطبيق يقوم بمحاولة بإنشاء اتصال بقواعد البيانات mysql ويظهر الخطأ التالي:

    I/System.out: Error ************************java.sql.SQLNonTransientConnectionException: Could not create connection to database server.
    W/System.err: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference
            at com.example.testjdbc.MainActivity.getUserList(MainActivity.java:54)
    W/System.err:     at com.example.testjdbc.MainActivity.showData(MainActivity.java:73)
    W/System.err:     at com.example.testjdbc.MainActivity.onCreate(MainActivity.java:24)
            at android.app.Activity.performCreate(Activity.java:7136)
    W/System.err:     at android.app.Activity.performCreate(Activity.java:7127)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:6669)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

     

    الكود:

    private Connection getConnection(){
            Connection con;
            try{
                Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
                con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testandroid?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=GMT","root","");
                return con;
            }catch (Exception e){
                System.out.println("Error :"+e);
                return null;
            }
        }
        private ArrayList<User> getUserList()
        {
            ArrayList<User> userList = new ArrayList<>();
            Connection connection = getConnection();
            String query = "Select pseudo FROM `users` where userID="+1;
            Statement st;
            ResultSet rs;
            try{
                st =  connection.createStatement();
                rs = st.executeQuery(query);
                User user ;
                while (rs.next())
                {
                    user = new User(rs.getString("pseudo"));
                    userList.add(user);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return userList;
        }
        private void showData(){
            ArrayList<User> list = getUserList();
            for (int i=0; i<list.size(); i++){
                test.setText(list.get(i).getPseudo());
                test.setText("gn");
            }
        }

     

    • أعجبني 1
  6. يحدث الخطأ عند إستدعاء الكود التالي:

    BottomSheetScaffold(
        scaffoldState = bottomSheetScaffoldState,
        sheetContent = { Text("anything") },
        sheetShape = Shapes.large,
        backgroundColor = AppTheme.colors.uiBackground,
        modifier = modifier
        
    ) { (content) }

    رسالة الخطأ:

    java.lang.IllegalArgumentException: The initial value must have an associated anchor.

    هل هناك أي إقتراحات لحل المشكلة ؟

    • أعجبني 1
  7. لدي تطبيق يقوم بعرض RSS Feed من موقع معين، يظهر لي الخطأ التالي عند تشغيل التطبيق:

    android.os.NetworkOnMainThreadException

    هذا هو الكود التي تحصل فيه المشكلة:

    URL url = new URL(urlToRssFeed);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    XMLReader xmlreader = parser.getXMLReader();
    RssHandler theRSSHandler = new RssHandler();
    xmlreader.setContentHandler(theRSSHandler);
    InputSource is = new InputSource(url.openStream());
    xmlreader.parse(is);
    return theRSSHandler.getFeed();

     

    • أعجبني 1
  8. لدي الكود التالي:

    public class Main {
        public static boolean calculateAge(LocalDate date) {
            LocalDate DateToday = LocalDate.now();
            Period period = Period.between(date, DateToday);
            int age = period.getYears();
            if (age>19){
                return true;
            }
            else{
                return false;
            }
        }  
        public static void main(String [] args) {
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter Date of Birth : dd-mm-yyyy");
            String dateEntered = sc.next();
            if(Pattern.matches("(0[1-9]|[12][0-9]|3[01])\\-(0[1-9]|[1][12])\\-([12][0-9][0-9][0-9])", dateEntered)){
                DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-mm-dd");
                LocalDate localDate= LocalDate.parse(dateEntered, dtf);
                calculateAge(localDate);
            }
            else{
                System.out.println("Wrong Date");
            }
        }
    }

    يحدث الخطأ التالي عند معالجة التاريخ المدخل من قبل المستخدم:

    Exception in thread "main" java.time.format.DateTimeParseException: Text '03-09-1999' could not be parsed at index 0 at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2051) at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1953) at java.base/java.time.LocalDate.parse(LocalDate.java:429) at java.base/java.time.LocalDate.parse(LocalDate.java:414) at Main.main(Main.java:26)

    ما هو سبب ظهور الخطأ ؟

  9. احاول معالجة كود xml بعد جلبه من موقع معين حيث يحدث الخطأ التالي:

    [Fatal Error] :1:1: Premature end of file.
    org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.
        at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
        at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)

    هذه هي الجزئية المسؤولة عن قراءة الكود:

    String eD = IOUtils.toString(request.getReader());
    DocumentBuilder db1 = null;
        try {
            db1 = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            
            e.printStackTrace();
        }
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(eD));
        
        Document doc1 = null;
        try {
            doc1 = db1.parse(is);
        } catch (SAXException e) {
            e.printStackTrace();
        }

    ما هو سبب المشكلة؟

  10. يحدث الخطأ " not a statement " أثناء إستدعاء الدالة التالية:

    public boolean binarySearch(int[] list, int target, int low, int high) {
            list ={"1,2,5,7,9,15"}; 
            target = 5;
            boolean result = binarySearch(list, target, 0, list.length-1);
            executions++;
            int mid = (low + high) / 2;
            if(!result){
                System.out.println("Target not found -- bad search.");
            }else{
                System.out.println("Target found -- sucessful search!");
            }    
            if (list[mid] == target) {
                return true;
            } else {
                if (low > high) {
                    return false;
                } else {
                    comparisons++;
                    if (list[mid] < target) {
                        return binarySearch(list, target, mid + 1, high);
                    } else {
                        return binarySearch(list, target, low, mid - 1);
                    }
                }

    لم أفهم ماذا تعني رسالة الخطأ ؟ وما هو الحل ؟

    • أعجبني 1
  11. لدي برنامج يقوم بقراءة ملف اكسيل ويرفع محتوياته الى قاعدة البيانات وهو يعمل بشكل جيد لكن في حال كانت خلية ما فارغة يظهر لي الخطأ التالي:

    java.lang.NullPointerException

    هذا هو الكود الذي يحصل فيه الخطأ:

    public void upload() throws IOException{
        String host="localhost";
        String port="543";
        String db_name="postgr";
        String username="root";
        String password="root";
        int max = 1000;
        int min = 0;
        String dir="C:\\Users\\User\\Desktop\\book.xlsx";
        int batchSize = 20;
        Connection connection = null;
        try {
            long start = System.currentTimeMillis();
            FileInputStream inputStream = new FileInputStream(dir);
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet firstSheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = firstSheet.iterator();
            try {
                Class.forName("org.postgresql.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            connection = DriverManager.getConnection("jdbc:postgresql://"+host+":"+port+"/"+db_name+"", ""+username+"", ""+password+"");
            connection.setAutoCommit(false);
            String sql = "INSERT INTO survey.tabledata (id,col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,surveyid) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
            PreparedStatement statement = connection.prepareStatement(sql);    
            int count = 0;
            while (rowIterator.hasNext()) {
                Row nextRow = rowIterator.next();
                Iterator<Cell> cellIterator = nextRow.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell nextCell = cellIterator.next();
                    int columnIndex = nextCell.getColumnIndex();
                    switch (columnIndex) {
                    case 0:
                        int col1 = (int) nextCell.getNumericCellValue(); 
                        statement.setInt(1,col1);
                        break;
                    case 1:
                        String col2 = nextCell.getStringCellValue();
                        statement.setString(2, col2);
                        break;
                    case 2:
                        String col3 = nextCell.getStringCellValue();
                        statement.setString(3, col3);
                        break;
                    case 3:
                        String col4 = nextCell.getStringCellValue();
                        statement.setString(4, col4);
                        break;
                    case 4:
                        String col5 = nextCell.getStringCellValue();
                        statement.setString(5, col5);
                        break;
                    case 5:
                        String col6 = nextCell.getStringCellValue();
                        statement.setString(6, col6);
                        break;
                    case 6:
                        String col7 = nextCell.getStringCellValue();
                        statement.setString(7, col7);
                        break;
                    case 7:
                        String col8 = nextCell.getStringCellValue();
                        statement.setString(8, col8);
                        break;
                    case 8:
                        String col9 = nextCell.getStringCellValue();
                        statement.setString(9, col9);
                        break;
    
                    case 9:
                        String col10 = nextCell.getStringCellValue();
                        statement.setString(10, col10);
                        break;
                    case 10:
                        String col11 = nextCell.getStringCellValue();
                        statement.setString(11, col11);
                        break;
                    case 11:
                        int col12 = (int) nextCell.getNumericCellValue();
                        statement.setInt(12,col12);
                        break;
                    }
                }
                statement.addBatch();
    
                if (count % batchSize == 0) {
                    statement.executeBatch();
                }              
            }
            statement.executeBatch();
            connection.commit();
            connection.close();
            long end = System.currentTimeMillis();
            System.out.printf("import done");
    
        } catch (IOException ex1) {
            System.out.println("Error");
            ex1.printStackTrace();
        } catch (SQLException ex2) {
            System.out.println("error");
            ex2.printStackTrace();
        }
    }

    كيف اتخطى تلك المشكلة ؟

  12. كتبت الكود التالي لإجراء إختبار للويب :

        public static void main(String[] args) {
            System.setProperty("webdriver.chrome.driver", "C:\\Users\\vikas\\Downloads\\chromedriver.exe");
    
            WebDriver driver = new ChromeDriver();
            driver.manage().window().maximize();
            driver.get("http://the-internet.herokuapp.com/");
            driver.findElement(By.xpath("(//div[@id='content']/ul)/li[33]")).click();
            driver.findElement(By.cssSelector("a[href*='windows']")).click();
            Set<String> windows = driver.getWindowHandles();
            Iterator<String> it = windows.iterator();
            String parentId = it.next();
            String childId = it.next();
            driver.switchTo().window(childId);
            System.out.println(driver.findElement(By.xpath("//h3[contains(text(),'New Window')]")).getText());
            driver.switchTo().window(parentId);
            System.out.println(driver.findElement(By.xpath("//div[@id='content']/div/h3")).getText());
        }
    
    }

    عند تنفيذه يظهر لي الخطأ التالي:

    Exception in thread "main" java.util.NoSuchElementException errorusing Selenium and Java

  13. يظهر لي الخطأ التالي عند محاولة كتابة الملفات:

    java.io.IOException: Access is denied at java.base/java.io.FileOutputStream.writeBytes(Native Method)

    هذا الجزء من الكود هو المسؤول عن كتابة الملفات في برنامجي:

    private static void writeTestCaseIntoFile(String fileName, ArrayList<String> strings) {
            File file = new File(fileName);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            FileWriter writer;
            try {
                writer = new FileWriter(file);
                for (String string : strings) {
                    try {
                        writer.write(string.trim() + "\n");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                writer.close();
                System.out.println("All OK! , " + fileName);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

     

    • أعجبني 1
  14. لدي برنامج مكون من قسمين:

    • قسم الـserver : يقوم بإستقبال عدد ما من الـclient ثم يعيد له مربع العدد.
    • قسم الـclient يقوم بإرسال عدد ما إلى الـserver ويستقبل النتيجة.

    المشكلة هي أن السيرفر يستقبل العدد مرة واحدة وبعد ذلك لا يستقبل أي شيء!

    الكود الخاص بالـclient:

    public class TestClient{
         public static void main(String args[]){
              try{
               String host=""+args[0];
               int port=Integer.parseInt(args[1]);
              BufferedReader input=new BufferedReader(new InputStreamReader(System.in));          
              String lettura=input.readLine();
              while(!lettura.equals("good")){
              Socket s=new Socket(host,port);
              PrintWriter output=new PrintWriter(s.getOutputStream());   
              output.println(lettura);
              output.flush();
              BufferedReader insok = new BufferedReader(new InputStreamReader(s.getInputStream()));    
              String lettsock=insok.readLine(); 
              System.out.println(lettsock);
              lettura=input.readLine();       
             }
              input.close();  
           }
             catch(Exception ex){
                System.out.println(ex);
                System.exit(3);
             }  
        }
    } 

    الكود الخاص بالـserver:

    public class TestServer{
       static final int PORT = 1024;
        public static void main(String args[]){
         try{
             ServerSocket ss=new ServerSocket(PORT);
              while(true) {
                   Socket ns = ss.accept();
                    BufferedReader networkIn = new BufferedReader(new InputStreamReader(ns.getInputStream()));
                    PrintWriter networkOut=new PrintWriter(ns.getOutputStream()); 
                    String line;
                    while ((line = networkIn.readLine()) != null) {
                      System.out.println(": " + line);
                      try{
                         int number=Integer.parseInt(line);
                         number=number*number;
                         networkOut.println(number);
                         networkOut.flush();
                       }
                      catch(Exception ex){
                      } 
                    }
                  ns.close();
                }
         }
        catch(Exception ex){
            System.out.println(ex);
            System.exit(3);
         }
       }
    }

     

  15. لدي البيانات التالية كـJSON:

    [
      {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "Sincere@april.biz",
        "address": {
          "street": "Kulas Light",
          "suite": "Apt. 556",
          "city": "Gwenborough",
          "zipcode": "92998-3874",
          "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
          }
        },
        "phone": "1-770-736-8031 x56442",
        "website": "hildegard.org",
        "company": {
          "name": "Romaguera-Crona",
          "catchPhrase": "Multi-layered client-server neural-net",
          "bs": "harness real-time e-markets"
        }
      },
      {
        "id": 2,
        "name": "Ervin Howell",
        "username": "Antonette",
        "email": "Shanna@melissa.tv",
        "address": {
          "street": "Victor Plains",
          "suite": "Suite 879",
          "city": "Wisokyburgh",
          "zipcode": "90566-7771",
          "geo": {
            "lat": "-43.9509",
            "lng": "-34.4618"
          }
        },
        "phone": "010-692-6593 x09125",
        "website": "anastasia.net",
        "company": {
          "name": "Deckow-Crist",
          "catchPhrase": "Proactive didactic contingency",
          "bs": "synergize scalable supply-chains"
        }
      },
      {
        "id": 3,
        "name": "Clementine Bauch",
        "username": "Samantha",
        "email": "Nathan@yesenia.net",
        "address": {
          "street": "Douglas Extension",
          "suite": "Suite 847",
          "city": "McKenziehaven",
          "zipcode": "59590-4157",
          "geo": {
            "lat": "-68.6102",
            "lng": "-47.0653"
          }
        },
        "phone": "1-463-123-4447",
        "website": "ramiro.info",
        "company": {
          "name": "Romaguera-Jacobson",
          "catchPhrase": "Face to face bifurcated interface",
          "bs": "e-enable strategic applications"
        }
      }
    ]

    كيف احول هذا البيانات إلى Object ؟

    • أعجبني 1
  16. يظهر الخطأ التالي عند محاولة الاتصال في قاعدة البيانات MySQL:

    Establishing SSL connection without server's identity verification is not recommended.

    هذا الكود الخاص بالـmain class:

    public class MyDatabaseTest {
    
        public static void main() {
            Database myDataBase = new Database();
            try {
                myDataBase.connect();
            } catch (Exception e) {
                e.printStackTrace();
            }
            myDataBase.close();
        }
    }

    هذا الكود الخاص بقاعدة البيانات:

    public class Database {
    
        private Connection myConnection;
    
        public void connect() throws Exception{
    
            if(myConnection != null) return;
    
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                throw new Exception("error");
            }
    
            String connectionURL = "jdbc:mysql://localhost:2000/";
    
            myConnection = DriverManager.getConnection(connectionURL, "root", "");        
        }
    
        public void close(){
            if(myConnection != null){
                try {
                    myConnection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

     

  17. يحدث الخطأ التالي عند استدعاء Scaffold.of(context) لإظهار snackbar :

    1.thumb.png.fb89d20c28cb664f5eb61c189c11fab3.png

    هذا هو الكود الخاص بالشاشة الذي يحدث بها الخطأ:

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyHomePage());
    
    class MyHomePage extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'test',
          theme: ThemeData(
            primarySwatch: Colors.cyan,
          ),
          home: Page1(),
        );
      }
    }
    class Page1 extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('page1'),
          ),
          body: Center(
            child: RaisedButton(
              color: Colors.cyan,
              textColor: Colors.white,
              onPressed: (){
    
                Scaffold.of(context).showSnackBar(SnackBar(content: Text('Hey there')));
              },
              child: Text('show snackbar'),
            ),
          ),
        );
      }
    }
    
    
    

     

    • أعجبني 2
×
×
  • أضف...